From e52880664b221a1d13a7c90c5bc39fd032070464 Mon Sep 17 00:00:00 2001 From: "databricks-ci-ghec-2[bot]" <184307802+databricks-ci-ghec-2[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:42:31 +0000 Subject: [PATCH] Release databricks-sdk-java --- .codegen/_last_sha | 2 +- CHANGELOG.md | 24 + databricks-sdk-java/lockfile.json | 2 +- databricks-sdk-java/pom.xml | 2 +- .../com/databricks/sdk/core/UserAgent.java | 2 +- .../com/databricks/sdk/mixin/FilesExt.java | 135 +++ .../sdk/mixin/FilesExtEndpointClients.java | 377 ++++++++ .../sdk/mixin/FilesExtPresigned.java | 423 +++++++++ .../sdk/mixin/FilesExtResponseRecorder.java | 93 ++ .../databricks/sdk/mixin/FilesExtRetry.java | 545 ++++++++++++ .../sdk/mixin/FilesExtUploadData.java | 412 +++++++++ .../sdk/mixin/FilesExtUploadPlan.java | 163 ++++ .../sdk/mixin/FilesExtUploadWalk.java | 407 +++++++++ .../service/aifunctions/AiDecideRequest.java | 5 +- .../sdk/service/apps/AppPermissionLevel.java | 1 + .../sdk/service/apps/AppThumbnail.java | 6 +- .../databricks/sdk/service/apps/AppsAPI.java | 7 +- .../sdk/service/apps/AppsService.java | 7 +- .../service/apps/AsyncUpdateAppRequest.java | 4 +- .../databricks/sdk/service/apps/Space.java | 37 + .../sdk/service/apps/SpaceSharingPolicy.java | 10 + .../sdk/service/apps/SpaceType.java | 12 + .../BatchUpdateOperationsRequest.java | 63 ++ .../BatchUpdateOperationsResponse.java | 49 ++ .../BundleDeploymentsAPI.java | 25 + .../BundleDeploymentsImpl.java | 35 + .../BundleDeploymentsService.java | 17 + .../CheckEnrollmentsRequest.java | 48 + .../CheckEnrollmentsResponse.java | 53 ++ .../service/bundledeployments/Operation.java | 12 +- .../UpdateOperationRequest.java | 16 +- .../sdk/service/catalog/AiGatewayAPI.java | 6 +- .../sdk/service/catalog/AiGatewayService.java | 6 +- .../service/catalog/CreateSkillRequest.java | 5 +- .../service/catalog/InferenceTableConfig.java | 23 +- .../service/catalog/ListSkillsRequest.java | 6 +- .../UpdateModelProviderServiceRequest.java | 13 +- .../catalog/UpdateModelServiceRequest.java | 6 +- .../service/catalog/UpdateSecretRequest.java | 8 +- .../service/domains/CreateDomainRequest.java | 4 +- .../service/domains/ListDomainsRequest.java | 7 +- .../service/domains/ListDomainsResponse.java | 4 +- .../service/domains/UpdateDomainRequest.java | 16 +- .../sdk/service/files/FilesAPI.java | 1 + .../sdk/service/files/FilesService.java | 1 + .../service/geniemigrate/DestinationKind.java | 1 - .../sdk/service/geniemigrate/Project.java | 5 +- .../service/geniemigrate/SourceDialect.java | 3 - .../service/geniemigrate/TargetFramework.java | 2 - .../CreateRestrictedSharingGroupRequest.java | 4 +- .../ListRestrictedSharingGroupsResponse.java | 5 +- .../sdk/service/iam/PermissionLevel.java | 1 + .../service/iam/RestrictedSharingGroup.java | 13 +- .../sdk/service/lakewatch/ResourceStatus.java | 5 +- .../sdk/service/ml/ExperimentsAPI.java | 2 +- .../sdk/service/ml/ExperimentsService.java | 2 +- .../sdk/service/ml/FirstDistinctFunction.java | 25 +- .../sdk/service/ml/FirstFunction.java | 22 +- .../sdk/service/ml/FirstNFunction.java | 25 +- .../sdk/service/ml/LastDistinctFunction.java | 25 +- .../sdk/service/ml/LastFunction.java | 22 +- .../sdk/service/ml/LastNFunction.java | 25 +- .../sdk/service/ml/LoggedModel.java | 3 +- .../sdk/service/ml/LoggedModelInfo.java | 2 +- .../MaterializationFailureNotification.java | 30 +- .../ml/MaterializationNotifications.java | 2 +- .../ml/MaterializationSetTriggerProgress.java | 5 +- .../sdk/service/ml/SawtoothWindow.java | 8 +- .../ml/TriggerMaterializationSetRequest.java | 3 +- .../GenerateDatabaseCredentialRequest.java | 9 +- .../service/postgres/ListProjectsRequest.java | 7 +- .../sdk/service/postgres/PostgresAPI.java | 16 +- .../sdk/service/postgres/PostgresService.java | 16 +- .../sdk/service/postgres/RequestedClaims.java | 7 +- .../service/postgres/RequestedResource.java | 2 +- .../sdk/service/sandbox/ComputeSpec.java | 47 +- .../sdk/service/sandbox/SandboxSpec.java | 19 +- .../sdk/service/sandbox/StorageSpec.java | 50 ++ .../sdk/service/serving/TelemetryConfig.java | 4 +- .../sdk/service/settings/AsanaConfig.java | 97 ++ .../settings/AsanaRuleTriggerTarget.java | 67 ++ .../settings/AsanaTaskCreationTarget.java | 46 + .../sdk/service/settings/Config.java | 34 +- .../settings/CreateOboTokenRequest.java | 2 +- .../settings/CreateOboTokenResponse.java | 2 +- .../sdk/service/settings/DestinationType.java | 2 + .../service/settings/ServiceNowConfig.java | 184 ++++ .../settings/ServiceNowTableScope.java | 12 + ...GetPublicAccountUserPreferenceRequest.java | 2 +- ...tchPublicAccountUserPreferenceRequest.java | 5 +- .../ReposAllowListPermissionMessage.java | 45 + ...sAllowListPermissionMessagePermission.java | 12 + .../sdk/service/settingsv2/Setting.java | 37 + .../service/settingsv2/UserPreference.java | 27 +- .../service/sql/DefaultWarehouseOverride.java | 13 +- ...UpdateDefaultWarehouseOverrideRequest.java | 8 +- .../sdk/service/sql/WarehousesAPI.java | 10 +- .../sdk/service/sql/WarehousesService.java | 10 +- .../sdk/mixin/FilesExtClientHarness.java | 149 ++++ .../sdk/mixin/FilesExtContractTest.java | 543 ++++++++++++ .../mixin/FilesExtEndpointClientsTest.java | 345 ++++++++ .../sdk/mixin/FilesExtFakeServer.java | 826 ++++++++++++++++++ .../sdk/mixin/FilesExtFakeServerTest.java | 302 +++++++ .../sdk/mixin/FilesExtPresignedTest.java | 510 +++++++++++ .../mixin/FilesExtResponseRecorderTest.java | 444 ++++++++++ .../sdk/mixin/FilesExtRetryTest.java | 703 +++++++++++++++ .../databricks/sdk/mixin/FilesExtTest.java | 342 ++++++++ .../databricks/sdk/mixin/FilesExtTests.java | 76 ++ .../sdk/mixin/FilesExtUploadDataTest.java | 668 ++++++++++++++ .../sdk/mixin/FilesExtUploadPlanTest.java | 178 ++++ .../sdk/mixin/FilesExtUploadWalkTest.java | 794 +++++++++++++++++ examples/docs/pom.xml | 2 +- examples/spring-boot-oauth-u2m-demo/pom.xml | 2 +- lockfile.json | 2 +- pom.xml | 2 +- shaded/pom.xml | 2 +- 116 files changed, 9834 insertions(+), 188 deletions(-) create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExt.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtEndpointClients.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtPresigned.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtResponseRecorder.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtRetry.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtUploadData.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtUploadPlan.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtUploadWalk.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/SpaceSharingPolicy.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/SpaceType.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BatchUpdateOperationsRequest.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BatchUpdateOperationsResponse.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/CheckEnrollmentsRequest.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/CheckEnrollmentsResponse.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/service/sandbox/StorageSpec.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/AsanaConfig.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/AsanaRuleTriggerTarget.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/AsanaTaskCreationTarget.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/ServiceNowConfig.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/ServiceNowTableScope.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/ReposAllowListPermissionMessage.java create mode 100644 databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/ReposAllowListPermissionMessagePermission.java create mode 100644 databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtClientHarness.java create mode 100644 databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtContractTest.java create mode 100644 databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtEndpointClientsTest.java create mode 100644 databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtFakeServer.java create mode 100644 databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtFakeServerTest.java create mode 100644 databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtPresignedTest.java create mode 100644 databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtResponseRecorderTest.java create mode 100644 databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtRetryTest.java create mode 100644 databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtTest.java create mode 100644 databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtTests.java create mode 100644 databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtUploadDataTest.java create mode 100644 databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtUploadPlanTest.java create mode 100644 databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtUploadWalkTest.java diff --git a/.codegen/_last_sha b/.codegen/_last_sha index 8d155ac4d..6e9603f95 100644 --- a/.codegen/_last_sha +++ b/.codegen/_last_sha @@ -1 +1 @@ -53e4c6273d2874b13429a178dbbc57b5aac59fbb \ No newline at end of file +87ad00d1beb89e2c7efa32e8d4df78b6a715a1fa \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 3be3a0506..d3761914e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Version changelog +## Release v0.187.0 (2026-12-02) + +### API Changes +* Add `batchUpdateOperations()` and `checkEnrollments()` methods for `workspaceClient.bundleDeployments()` service. +* Add `sharingPolicy` and `spaceType` fields for `com.databricks.sdk.service.apps.Space`. +* Add `disabled` field for `com.databricks.sdk.service.catalog.InferenceTableConfig`. +* Add `ignoreNulls` field for `com.databricks.sdk.service.ml.FirstDistinctFunction`. +* Add `ignoreNulls` field for `com.databricks.sdk.service.ml.FirstFunction`. +* Add `ignoreNulls` field for `com.databricks.sdk.service.ml.FirstNFunction`. +* Add `ignoreNulls` field for `com.databricks.sdk.service.ml.LastDistinctFunction`. +* Add `ignoreNulls` field for `com.databricks.sdk.service.ml.LastFunction`. +* Add `ignoreNulls` field for `com.databricks.sdk.service.ml.LastNFunction`. +* Add `cpu` and `memoryMib` fields for `com.databricks.sdk.service.sandbox.ComputeSpec`. +* Add `storage` field for `com.databricks.sdk.service.sandbox.SandboxSpec`. +* Add `asana` and `serviceNow` fields for `com.databricks.sdk.service.settings.Config`. +* Add `effectiveRepoAllowlistPermission` and `repoAllowlistPermission` fields for `com.databricks.sdk.service.settingsv2.Setting`. +* Add `CAN_BUILD` enum value for `com.databricks.sdk.service.apps.AppPermissionLevel`. +* Add `CAN_BUILD` enum value for `com.databricks.sdk.service.iam.PermissionLevel`. +* Add `ASANA` and `SERVICE_NOW` enum values for `com.databricks.sdk.service.settings.DestinationType`. +* [Breaking] Remove `finalAttemptOnly` field for `com.databricks.sdk.service.ml.MaterializationFailureNotification`. +* [Breaking] Remove `DESTINATION_KIND_DESIGNER_FILE` enum value for `com.databricks.sdk.service.geniemigrate.DestinationKind`. +* [Breaking] Remove `SOURCE_DIALECT_INFORMATICA`, `SOURCE_DIALECT_SSIS` and `SOURCE_DIALECT_ALTERYX` enum values for `com.databricks.sdk.service.geniemigrate.SourceDialect`. +* [Breaking] Remove `TARGET_FRAMEWORK_SPARK_DECLARATIVE_PIPELINES` and `TARGET_FRAMEWORK_DESIGNER` enum values for `com.databricks.sdk.service.geniemigrate.TargetFramework`. + ## Release v0.186.0 (2026-11-25) ### API Changes diff --git a/databricks-sdk-java/lockfile.json b/databricks-sdk-java/lockfile.json index d744d2000..e9e79a9d8 100644 --- a/databricks-sdk-java/lockfile.json +++ b/databricks-sdk-java/lockfile.json @@ -1,7 +1,7 @@ { "artifactId": "databricks-sdk-java", "groupId": "com.databricks", - "version": "0.186.0", + "version": "0.187.0", "lockFileVersion": 1, "dependencies": [ { diff --git a/databricks-sdk-java/pom.xml b/databricks-sdk-java/pom.xml index d80beb456..b12765ec5 100644 --- a/databricks-sdk-java/pom.xml +++ b/databricks-sdk-java/pom.xml @@ -5,7 +5,7 @@ com.databricks databricks-sdk-parent - 0.186.0 + 0.187.0 databricks-sdk-java Databricks SDK for Java diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/core/UserAgent.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/core/UserAgent.java index 945863bf1..a546f97b1 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/core/UserAgent.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/core/UserAgent.java @@ -36,7 +36,7 @@ public String getValue() { // TODO: check if reading from // /META-INF/maven/com.databricks/databrics-sdk-java/pom.properties // or getClass().getPackage().getImplementationVersion() is enough. - private static final String version = "0.186.0"; + private static final String version = "0.187.0"; public static void withProduct(String product, String productVersion) { UserAgent.product = product; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExt.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExt.java new file mode 100644 index 000000000..e92965b37 --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExt.java @@ -0,0 +1,135 @@ +package com.databricks.sdk.mixin; + +import com.databricks.sdk.WorkspaceClient; +import com.databricks.sdk.core.ApiClient; +import com.databricks.sdk.core.DatabricksConfig; +import com.databricks.sdk.core.logging.LoggerFactory; +import com.databricks.sdk.core.retry.NoRetryStrategyPicker; +import com.databricks.sdk.service.files.FilesAPI; +import com.databricks.sdk.service.files.FilesService; + +/** + * The Files API, with the client of the Files transfer extension. Use {@link #of(WorkspaceClient)} + * to reach the methods that {@code workspaceClient.files()} does not declare. Upload and download + * are the generated single-request calls. + * + *

The extension needs the client's {@link DatabricksConfig}. A {@code FilesExt} built with one + * has a copy of the API client that sends each workspace call once. A {@code FilesExt} built + * without one, from an {@link ApiClient} alone or from a mock {@link FilesService}, has no + * extension: the classic {@link ApiClient} cannot be copied without its retries. + */ +public class FilesExt extends FilesAPI { + /** + * The workspace API client the transfer extension sends through, one attempt per call, or null if + * this {@code FilesExt} has no extension. + */ + private final ApiClient singleAttemptApiClient; + + /** A {@code FilesExt} without the transfer extension: see the class documentation. */ + public FilesExt(ApiClient apiClient) { + super(apiClient); + this.singleAttemptApiClient = null; + } + + /** + * A {@code FilesExt} with the transfer extension, as {@code WorkspaceClient} builds it; use + * {@link #of(WorkspaceClient)} to get one. {@code config} must be the configuration {@code + * apiClient} was built from, or the generated calls and the extension's would use different + * clients. + * + *

It never throws for the extension, which must not fail what works without it. If {@code + * config} gives another HTTP client than {@code apiClient} has, or its single-attempt client + * cannot be built, it logs a warning and has no extension. + */ + public FilesExt(ApiClient apiClient, DatabricksConfig config) { + super(apiClient); + this.singleAttemptApiClient = singleAttemptApiClientOrNull(apiClient, config); + } + + /** A {@code FilesExt} over a mock, without the transfer extension. */ + public FilesExt(FilesService mock) { + super(mock); + this.singleAttemptApiClient = null; + } + + /** + * Returns {@code workspaceClient.files()} as a {@code FilesExt}: the same object if it is one, + * otherwise one over the same {@link FilesService}, which has no transfer extension. + */ + public static FilesExt of(WorkspaceClient workspaceClient) { + FilesAPI files = workspaceClient.files(); + if (files == null) { + throw new IllegalStateException( + "workspaceClient.files() is not set; set it with withFilesAPI or withFilesImpl"); + } + if (files instanceof FilesExt) { + return (FilesExt) files; + } + FilesService service = files.impl(); + if (service == null) { + throw new IllegalStateException( + "workspaceClient.files() has no FilesService; tests that call FilesExt.of(w) should" + + " inject mock(FilesExt.class) with withFilesAPI"); + } + return new FilesExt(service); + } + + /** Whether transfers use the extension rather than the generated single-request path. */ + boolean hasTransferExtension() { + return singleAttemptApiClient != null; + } + + /** The workspace API client of the transfer extension, or null without one. */ + ApiClient singleAttemptApiClient() { + return singleAttemptApiClient; + } + + /** What the single-attempt workspace client's responses said, or null without the extension. */ + FilesExtResponseRecorder workspaceResponses() { + return singleAttemptApiClient == null + ? null + : (FilesExtResponseRecorder) singleAttemptApiClient.getHttpClient(); + } + + /** + * A copy of the API client {@code config} gives that sends each call once. The user's own client + * and config keep their retries. + */ + private static ApiClient singleAttemptApiClientOrNull( + ApiClient apiClient, DatabricksConfig config) { + try { + DatabricksConfig resolved = resolved(config); + if (apiClient.getHttpClient() != resolved.getHttpClient()) { + warnWithoutExtension( + "the config is not the one the API client was built from: they have different HTTP" + + " clients"); + return null; + } + return singleAttemptApiClient(resolved); + } catch (RuntimeException e) { + warnWithoutExtension("its single-attempt API client could not be built: " + e); + return null; + } + } + + private static void warnWithoutExtension(String reason) { + // Looked up here, not held in a field, so that the logger factory in use applies. + LoggerFactory.getLogger(FilesExt.class) + .warn( + "The Files transfer extension is off, using the generated upload and download: {}", + reason); + } + + private static ApiClient singleAttemptApiClient(DatabricksConfig resolved) { + return new ApiClient.Builder() + .withDatabricksConfig(resolved) + .withHttpClient(new FilesExtResponseRecorder(resolved.getHttpClient())) + .withRetryStrategyPicker(new NoRetryStrategyPicker()) + .build(); + } + + private static DatabricksConfig resolved(DatabricksConfig config) { + // ApiClient(config) has resolved it already; resolving again would fetch host metadata again. + return config.getHttpClient() == null ? config.resolve() : config; + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtEndpointClients.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtEndpointClients.java new file mode 100644 index 000000000..623c16d33 --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtEndpointClients.java @@ -0,0 +1,377 @@ +package com.databricks.sdk.mixin; + +import com.databricks.sdk.core.ApiClient; +import com.databricks.sdk.core.DatabricksError; +import com.databricks.sdk.core.error.ApiErrors; +import com.databricks.sdk.core.http.Encoding; +import com.databricks.sdk.core.http.HttpClient; +import com.databricks.sdk.core.http.Request; +import com.databricks.sdk.core.http.Response; +import com.databricks.sdk.core.logging.Logger; +import com.databricks.sdk.core.logging.LoggerFactory; +import com.databricks.sdk.core.utils.Timer; +import com.databricks.sdk.mixin.FilesExtRetry.Budget; +import com.databricks.sdk.mixin.FilesExtRetry.Failure; +import com.databricks.sdk.mixin.FilesExtRetry.RequestFailed; +import com.databricks.sdk.mixin.FilesExtRetry.Result; +import com.databricks.sdk.mixin.FilesExtRetry.Send; +import com.databricks.sdk.mixin.FilesExtRetry.TransferStatus; +import com.databricks.sdk.mixin.FilesExtUploadWalk.MultipartSession; +import com.databricks.sdk.mixin.FilesExtUploadWalk.UploadClient; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.StringJoiner; +import java.util.TreeMap; +import java.util.function.BooleanSupplier; +import org.apache.commons.io.IOUtils; + +/** + * What the endpoint clients share: the transfer's HTTP clients, budgets and request helpers, and + * the Files API 2.0 client on the workspace host, which takes a single shot. The presigned client + * is {@link FilesExtPresigned}. + * + *

Every workspace call goes through {@link Transfer#execute}: the single-attempt API client and + * {@link FilesExtRetry#onWorkspace}, so the retry loop sees each response's status and Retry-After. + */ +final class FilesExtEndpointClients { + private FilesExtEndpointClients() {} + + private static final Logger LOG = LoggerFactory.getLogger(FilesExtEndpointClients.class); + private static final ObjectMapper MAPPER = new ObjectMapper(); + + /** The workspace Files API takes a single request of at most this many bytes. */ + static final long WORKSPACE_MAX_SINGLE_SHOT_SIZE = 5L * 1024 * 1024 * 1024; + + private static final DateTimeFormatter RFC_3339_SECONDS = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(ZoneOffset.UTC); + + static final String FILES_API_PATH = "/api/2.0/fs/files"; + + /** What every client of one transfer shares: the HTTP clients, the clock and the budgets. */ + static final class Transfer { + final ApiClient workspace; + final FilesExtResponseRecorder responses; + final HttpClient cloud; + final String host; + final String workspaceIdOrNull; + final Timer timer; + final Clock clock; + final Duration retryTimeout; + final int cloudMaxRetries; + final int urlRefreshes; + final Duration urlExpiration; + + /** + * @param workspace the single-attempt workspace API client, whose HTTP client is {@code + * responses} + * @param cloud the configured HTTP client, for requests that carry their own authorization + */ + Transfer( + ApiClient workspace, + FilesExtResponseRecorder responses, + HttpClient cloud, + String host, + String workspaceIdOrNull, + Timer timer, + Clock clock, + Duration retryTimeout) { + this.workspace = workspace; + this.responses = responses; + this.cloud = cloud; + this.host = host; + this.workspaceIdOrNull = workspaceIdOrNull; + this.timer = timer; + this.clock = clock; + this.retryTimeout = retryTimeout; + // The defaults of the cloud retries and of the presigned part URLs. + this.cloudMaxRetries = 3; + this.urlRefreshes = 3; + this.urlExpiration = Duration.ofHours(1); + } + + /** The API client's budget: no attempt cap, the retry timeout in all. */ + Budget apiClientBudget() { + return new Budget(null, retryTimeout); + } + + /** The bounded budget for hosts other than the workspace, so a failing host gives way fast. */ + Budget cloudBudget() { + return new Budget(cloudMaxRetries, retryTimeout); + } + + /** A call to the workspace through the single-attempt client, retried on this budget. */ + Result workspaceCall(Send send, Budget budget, TransferStatus status) { + return workspaceCall(send, budget, status, null); + } + + /** As above, sent again only while {@code canRetry} allows, or always if it is null. */ + Result workspaceCall( + Send send, Budget budget, TransferStatus status, BooleanSupplier canRetry) { + return FilesExtRetry.retry( + send, FilesExtRetry::commonDecision, budget, status, timer, null, canRetry); + } + + /** + * Sends one request to the workspace through the single-attempt client: see {@link + * FilesExtRetry#onWorkspace}. + */ + FilesExtRetry.Answered execute(Request request, Class type) + throws IOException, RequestFailed { + return FilesExtRetry.onWorkspace(workspace, responses, request, type); + } + + /** POSTs to the workspace and parses the JSON answer, {} for an empty one. */ + JsonNode postJson(String path, Map query, Object bodyOrNull) + throws IOException, RequestFailed { + String url = withQuery(path, query); + // An empty body as a string, so it is sent with Content-Length: 0. A request with no body + // at all is logged with its URL, query included, by the default HTTP client. + Request request = + bodyOrNull == null + ? new Request("POST", url, "") + : new Request("POST", url, toJson(bodyOrNull)) + .withHeader("Content-Type", "application/json"); + request.withHeader("Accept", "application/json"); + String text; + try (InputStream body = execute(request, InputStream.class).value) { + text = body == null ? "" : IOUtils.toString(body, StandardCharsets.UTF_8); + } + try { + return text.isEmpty() ? MAPPER.createObjectNode() : MAPPER.readTree(text); + } catch (JsonProcessingException e) { + // Not a dropped connection: an answer that isn't JSON, which walks. + throw unexpected(text); + } + } + + /** The RFC 3339 time a presigned URL may be used until. */ + String urlExpireTime() { + return RFC_3339_SECONDS.format(clock.instant().plus(urlExpiration)); + } + } + + private static String toJson(Object body) { + try { + return MAPPER.writeValueAsString(body); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Unable to serialize a request body", e); + } + } + + /** The workspace path of a file in the Files API 2.0. */ + static String filesApiPath(String path) { + String escaped = Encoding.encodeMultiSegmentPathParameter(path); + // Mirrors the API client, which collapses a doubled leading slash in Files API paths. + return FILES_API_PATH + (escaped.startsWith("//") ? escaped.substring(1) : escaped); + } + + /** The scheme, host and port of a URL, normalized so that two spellings compare equal. */ + static String origin(String url) { + URI uri; + try { + uri = URI.create(url); + } catch (IllegalArgumentException e) { + // Unparsable: equal only to itself. + return url; + } + if (uri.getScheme() == null || uri.getHost() == null) { + return url; + } + String scheme = uri.getScheme().toLowerCase(); + int port = + uri.getPort() != -1 + ? uri.getPort() + : scheme.equals("https") ? 443 : scheme.equals("http") ? 80 : -1; + return scheme + "://" + uri.getHost().toLowerCase() + ":" + port; + } + + static void requireWorkspaceHost(FilesExtEndpoint endpoint, Transfer transfer) { + if (!origin(endpoint.baseUrl()).equals(origin(transfer.host))) { + throw new IllegalArgumentException( + endpoint.kind() + " at " + endpoint.baseUrl() + " is not on the workspace host"); + } + } + + static IllegalArgumentException unexpected(Object response) { + return new IllegalArgumentException("Unexpected server response: " + response); + } + + /** + * Maps an unsuccessful data-plane response to an SDK error: its Databricks JSON error if it has + * one, otherwise {@code message}, typed by the status code. + */ + static DatabricksError responseError(Response response, String message) { + return responseError(response, readBody(response), message); + } + + /** The body of a response, read and closed, or "" if it can't be read. */ + static String readBody(Response response) { + try (InputStream in = response.getBody()) { + return in == null ? "" : IOUtils.toString(in, StandardCharsets.UTF_8); + } catch (IOException e) { + // The status alone still types the error. + return ""; + } + } + + /** As above, for a response whose body was already read. */ + static DatabricksError responseError(Response response, String body, String message) { + boolean databricksError = false; + try { + JsonNode json = MAPPER.readTree(body); + databricksError = json != null && (json.has("error_code") || json.has("message")); + } catch (IOException e) { + // Not JSON: cloud storage answers in XML. + } + String errorBody; + try { + errorBody = + databricksError + ? body + : MAPPER.writeValueAsString(Collections.singletonMap("message", message)); + } catch (IOException e) { + errorBody = "{}"; + } + return ApiErrors.getDatabricksError( + new Response( + response.getRequest(), + response.getStatusCode(), + response.getStatus(), + response.getAllHeaders(), + errorBody)); + } + + /** + * {@code url} with {@code query} appended, encoded as the SDK encodes query params: names in + * order, each name and value form-encoded as UTF-8. The query is put in the URL rather than added + * with {@code withQueryParam}, so the request is sent with its URL as is and the escapes of the + * file path are kept. + */ + static String withQuery(String url, Map query) { + if (query.isEmpty()) { + return url; + } + StringJoiner joiner = new StringJoiner("&"); + for (Map.Entry param : new TreeMap<>(query).entrySet()) { + joiner.add(formEncode(param.getKey()) + "=" + formEncode(param.getValue())); + } + return url + (url.contains("?") ? "&" : "?") + joiner; + } + + private static String formEncode(String s) { + try { + return URLEncoder.encode(s, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException("UTF-8 is not supported", e); + } + } + + static Map query(String... namesAndValues) { + Map query = new LinkedHashMap<>(); + for (int i = 0; i < namesAndValues.length; i += 2) { + query.put(namesAndValues[i], namesAndValues[i + 1]); + } + return query; + } + + /** + * FILES_API 2.0 on the workspace host: a single shot of at most {@link + * #WORKSPACE_MAX_SINGLE_SHOT_SIZE}, with the API client's budget. Its multipart session, used + * through the storage proxy, comes with the endpoint clients beyond the built-in order. + */ + static final class WorkspaceFilesClient implements UploadClient { + private final Transfer transfer; + private final FilesExtEndpoint endpoint; + + WorkspaceFilesClient(Transfer transfer, FilesExtEndpoint endpoint) { + requireWorkspaceHost(endpoint, transfer); + this.transfer = transfer; + this.endpoint = endpoint; + } + + @Override + public String name() { + return endpoint.kind() + " at " + endpoint.baseUrl(); + } + + @Override + public boolean supportsMultipart() { + return false; + } + + @Override + public boolean supportsSingleShot() { + return true; + } + + @Override + public Long maxSingleShotSizeOrNull() { + return WORKSPACE_MAX_SINGLE_SHOT_SIZE; + } + + @Override + public Long maxPartSizeOrNull() { + return null; + } + + @Override + public Failure putFile( + String path, Boolean overwriteOrNull, FilesExtUploadData data, TransferStatus status) { + LOG.debug("Using single-shot upload for input stream"); + Result result = + transfer.workspaceCall( + () -> send(path, overwriteOrNull, data), + transfer.apiClientBudget(), + status, + data::canSendAgain); + return result.failed() ? result.failure : null; + } + + private Void send(String path, Boolean overwriteOrNull, FilesExtUploadData data) + throws IOException, RequestFailed { + Long size = data.sizeOrNull(); + // An empty body as a string, as an empty stream would go chunked, without the length these + // hosts require. + String url = + withQuery( + filesApiPath(path), + overwriteOrNull == null + ? Collections.emptyMap() + : query("overwrite", overwriteOrNull.toString())); + Request request = + Objects.equals(size, 0L) + ? new Request("PUT", url, "") + : new Request("PUT", url, data.whole()); + if (size != null && size > 0) { + request.withHeader("Content-Length", size.toString()); + } + request.withHeader("Content-Type", "application/octet-stream"); + if (transfer.workspaceIdOrNull != null) { + request.withHeader("X-Databricks-Workspace-Id", transfer.workspaceIdOrNull); + } + transfer.execute(request, Void.class); + return null; + } + + @Override + public Result initiateUpload( + String path, Boolean overwriteOrNull, TransferStatus status, int batchSize) { + throw new UnsupportedOperationException("The workspace Files API client takes single shots"); + } + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtPresigned.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtPresigned.java new file mode 100644 index 000000000..a509c8986 --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtPresigned.java @@ -0,0 +1,423 @@ +package com.databricks.sdk.mixin; + +import com.databricks.sdk.core.http.Request; +import com.databricks.sdk.core.http.Response; +import com.databricks.sdk.core.logging.Logger; +import com.databricks.sdk.core.logging.LoggerFactory; +import com.databricks.sdk.mixin.FilesExtRetry.Decision; +import com.databricks.sdk.mixin.FilesExtRetry.Failure; +import com.databricks.sdk.mixin.FilesExtRetry.RequestFailed; +import com.databricks.sdk.mixin.FilesExtRetry.Result; +import com.databricks.sdk.mixin.FilesExtRetry.Send; +import com.databricks.sdk.mixin.FilesExtRetry.TransferStatus; +import com.databricks.sdk.mixin.FilesExtRetry.UrlExpired; +import com.databricks.sdk.mixin.FilesExtUploadWalk.MultipartSession; +import com.databricks.sdk.mixin.FilesExtUploadWalk.UploadClient; +import com.fasterxml.jackson.databind.JsonNode; +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.regex.Pattern; +import javax.xml.parsers.DocumentBuilderFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +/** + * The presigned (IO_OFFLOAD) endpoint client: the session and the part URLs come from the Files API + * 2.0 on the workspace host, and the parts go to cloud storage URLs the workspace presigns, through + * the configured HTTP client without credentials and with a Content-Length, as cloud storage + * requires. No single shot. + */ +final class FilesExtPresigned { + private FilesExtPresigned() {} + + private static final Logger LOG = LoggerFactory.getLogger(FilesExtPresigned.class); + + static final String UPLOAD_PART_URLS_PATH = "/api/2.0/fs/create-upload-part-urls"; + + /** A URL's query, to cut: a signed URL carries its signature there. */ + private static final Pattern URL_QUERY = Pattern.compile("(\\S)\\?\\S+"); + + /** Whether a response is one of the cloud storage providers' "URL expired" errors. */ + static boolean isUrlExpired(int status, String body) { + if (status != 400 && status != 403) { + return false; + } + try { + Element root = errorRoot(body); + if (root == null) { + return false; + } + String code = child(root, "Code"); + if ("ExpiredToken".equals(code)) { + // GCP, and AWS when the URL was signed with temporary credentials that have since expired. + return true; + } + if ("AuthenticationFailed".equals(code)) { + // Azure + String details = child(root, "AuthenticationErrorDetail"); + return details != null + && details.contains("Signature not valid in the specified time frame"); + } + // AWS + return "AccessDenied".equals(code) && "Request has expired".equals(child(root, "Message")); + } catch (Exception e) { + return false; + } + } + + /** + * A cloud storage error for an error message: the status, and the provider's error code and + * message when the body is its XML error. The rest of the body is left out, since it can echo the + * request, the URL's signature included, and a URL's query is cut from the message for the same + * reason. + */ + static String cloudError(int status, String body) { + StringBuilder error = new StringBuilder("Response status: ").append(status); + try { + Element root = errorRoot(body); + String code = root == null ? null : child(root, "Code"); + String message = root == null ? null : child(root, "Message"); + if (code != null) { + error.append(", code: ").append(code.trim()); + } + if (message != null) { + error.append(", message: ").append(URL_QUERY.matcher(message.trim()).replaceAll("$1")); + } + } catch (Exception e) { + // Not the provider's XML error: the status alone. + } + return error.toString(); + } + + /** The root of a cloud storage XML error, or null if the body is XML but not an error. */ + private static Element errorRoot(String body) throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + Document doc = + factory + .newDocumentBuilder() + .parse(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8))); + Element root = doc.getDocumentElement(); + return root.getTagName().equals("Error") ? root : null; + } + + /** The text of the first direct child named {@code name}: nested elements are not searched. */ + private static String child(Element parent, String name) { + NodeList nodes = parent.getChildNodes(); + for (int i = 0; i < nodes.getLength(); i++) { + if (nodes.item(i) instanceof Element && ((Element) nodes.item(i)).getTagName().equals(name)) { + return nodes.item(i).getTextContent(); + } + } + return null; + } + + private static Map partsBody(Map etags) { + List> parts = new ArrayList<>(); + new TreeMap<>(etags) + .forEach( + (number, etag) -> { + Map part = new LinkedHashMap<>(); + part.put("part_number", number); + part.put("etag", etag); + parts.add(part); + }); + return Collections.singletonMap("parts", parts); + } + + /** A presigned URL and the headers it must be sent with. */ + static final class PresignedUrl { + final String url; + final Map headers; + final int partNumber; + + PresignedUrl(String url, Map headers, int partNumber) { + this.url = url; + this.headers = headers; + this.partNumber = partNumber; + } + } + + /** + * IO_OFFLOAD: parts go to presigned URLs on cloud storage, without credentials; the session and + * the URLs come from the Files API 2.0 on the workspace host. No single shot. + */ + static final class PresignedClient implements UploadClient { + private final FilesExtEndpointClients.Transfer transfer; + private final FilesExtEndpoint endpoint; + + PresignedClient(FilesExtEndpointClients.Transfer transfer, FilesExtEndpoint endpoint) { + FilesExtEndpointClients.requireWorkspaceHost(endpoint, transfer); + this.transfer = transfer; + this.endpoint = endpoint; + } + + @Override + public String name() { + return endpoint.kind() + " at " + endpoint.baseUrl(); + } + + @Override + public boolean supportsMultipart() { + return endpoint.multipartUploadSupported(); + } + + @Override + public boolean supportsSingleShot() { + return false; + } + + @Override + public Long maxSingleShotSizeOrNull() { + return null; + } + + @Override + public Long maxPartSizeOrNull() { + return null; + } + + /** + * A call that coordinates the presigned URLs: on the workspace, with the API client's budget. + */ + Result control(Send send, TransferStatus status) { + return transfer.workspaceCall(send, transfer.apiClientBudget(), status); + } + + @Override + public Failure putFile( + String path, Boolean overwriteOrNull, FilesExtUploadData data, TransferStatus status) { + throw new UnsupportedOperationException("The offload path has no single-shot upload"); + } + + @Override + public Result initiateUpload( + String path, Boolean overwriteOrNull, TransferStatus status, int batchSize) { + Map query = FilesExtEndpointClients.query("action", "initiate-upload"); + if (overwriteOrNull != null) { + query.put("overwrite", overwriteOrNull.toString()); + } + Result response = + control( + () -> transfer.postJson(FilesExtEndpointClients.filesApiPath(path), query, null), + status); + if (response.failed()) { + return Result.failed(response.failure); + } + String token = response.value.path("multipart_upload").path("session_token").asText(""); + if (token.isEmpty()) { + return Result.failed( + new Failure(FilesExtEndpointClients.unexpected(response.value), Decision.WALK)); + } + return Result.of(new PresignedSession(this, path, token, batchSize)); + } + } + + /** A multipart upload whose parts go to presigned URLs, requested a batch at a time. */ + static final class PresignedSession implements MultipartSession { + private final PresignedClient client; + private final FilesExtEndpointClients.Transfer transfer; + private final String path; + private final String token; + private final int batchSize; + private final Map urls = new HashMap<>(); + private Failure failureOrNull; + + PresignedSession(PresignedClient client, String path, String token, int batchSize) { + this.client = client; + this.transfer = client.transfer; + this.path = path; + this.token = token; + this.batchSize = batchSize; + } + + /** The part's presigned URL, asking for a batch if it has none, or the session's failure. */ + private Result partUrl(int number, TransferStatus status) { + synchronized (urls) { + if (failureOrNull != null) { + return Result.failed(failureOrNull); + } + PresignedUrl url = urls.get(number); + if (url != null) { + return Result.of(url); + } + } + Map body = new LinkedHashMap<>(); + body.put("path", path); + body.put("session_token", token); + body.put("start_part_number", number); + body.put("count", batchSize); + body.put("expire_time", transfer.urlExpireTime()); + Result> result = + client.control( + () -> + parseUrls( + transfer.postJson( + UPLOAD_PART_URLS_PATH, FilesExtEndpointClients.query(), body)), + status); + synchronized (urls) { + if (result.failed()) { + failureOrNull = result.failure; + return Result.failed(failureOrNull); + } + for (PresignedUrl url : result.value) { + urls.put(url.partNumber, url); + } + PresignedUrl url = urls.get(number); + if (url == null) { + failureOrNull = + new Failure( + FilesExtEndpointClients.unexpected("no URL for part " + number), Decision.WALK); + return Result.failed(failureOrNull); + } + return Result.of(url); + } + } + + /** + * The part URLs of a create-upload-part-urls answer. A malformed answer fails by naming what is + * wrong, not with the answer itself, which holds other parts' signed URLs. + */ + static List parseUrls(JsonNode response) { + JsonNode list = response.path("upload_part_urls"); + if (!list.isArray() || list.size() == 0) { + throw FilesExtEndpointClients.unexpected( + "upload_part_urls is missing, empty or not a list"); + } + List urls = new ArrayList<>(); + for (int i = 0; i < list.size(); i++) { + JsonNode part = list.get(i); + if (!part.path("url").isTextual()) { + throw FilesExtEndpointClients.unexpected("upload_part_urls[" + i + "] has no url"); + } + if (!part.path("part_number").canConvertToInt()) { + throw FilesExtEndpointClients.unexpected( + "upload_part_urls[" + i + "] has no integer part_number"); + } + Map headers = new LinkedHashMap<>(); + headers.put("Content-Type", "application/octet-stream"); + for (JsonNode h : part.path("headers")) { + headers.put(h.path("name").asText(), h.path("value").asText()); + } + urls.add( + new PresignedUrl(part.get("url").asText(), headers, part.get("part_number").asInt())); + } + return urls; + } + + private String putOnce(int number, byte[] data, TransferStatus status) throws Exception { + Result url = partUrl(number, status); + if (url.failed()) { + throw new RequestFailed(url.failure.error, null, url.failure.decision); + } + PresignedUrl presigned = url.value; + LOG.debug("Uploading part {}", number); + Request request = + new Request("PUT", presigned.url, new ByteArrayInputStream(data)) + .withHeaders(presigned.headers) + .withHeader("Content-Length", String.valueOf(data.length)); + Response response = transfer.cloud.execute(request); + int code = response.getStatusCode(); + // Read and closed either way, so a streaming HTTP client's connection is released. + String body = FilesExtEndpointClients.readBody(response); + if (code == 200 || code == 201) { + String etag = response.getFirstHeader("ETag"); + return etag == null ? "" : etag; + } + if (isUrlExpired(code, body)) { + LOG.debug("Upload URL expired, retrying..."); + synchronized (urls) { + urls.remove(number); + } + throw new UrlExpired("The presigned upload URL expired"); + } + // The body is not passed on: a JSON error from the cloud or a proxy may echo the signed URL. + throw new RequestFailed( + FilesExtEndpointClients.responseError( + response, "", "Unsuccessful chunk upload. " + cloudError(code, body)), + code, + null); + } + + private static Decision decide(Exception failure) { + if (failure instanceof UrlExpired) { + // Not retried here: the caller replaces the URL, up to its own limit. + return Decision.WALK; + } + return FilesExtRetry.commonDecision(failure); + } + + @Override + public Result putPart(int number, byte[] data, TransferStatus status) { + for (int refreshes = 0; ; refreshes++) { + Result result = + FilesExtRetry.retry( + () -> putOnce(number, data, status), + PresignedSession::decide, + transfer.cloudBudget(), + status, + transfer.timer); + if (!(result.failed() && result.failure.error instanceof UrlExpired) + || status.cancelled()) { + return result; + } + if (refreshes >= transfer.urlRefreshes) { + // Don't confuse the user with an unrelated "Permission denied" error. + return Result.failed( + new Failure( + new IllegalArgumentException( + "Unsuccessful chunk upload: upload URL expired after " + + refreshes + + " retries"), + Decision.WALK)); + } + } + } + + @Override + public Failure complete(Map etags, TransferStatus status) { + Result result = + client.control( + () -> + transfer.postJson( + FilesExtEndpointClients.filesApiPath(path), + FilesExtEndpointClients.query( + "action", + "complete-upload", + "upload_type", + "multipart", + "session_token", + token), + partsBody(etags)), + status); + return result.failed() ? result.failure : null; + } + + @Override + public void abort() { + // An interrupted upload still aborts its session, so the request is sent with the flag clear. + boolean interrupted = Thread.interrupted(); + try { + transfer.postJson( + FilesExtEndpointClients.filesApiPath(path), + FilesExtEndpointClients.query( + "action", "abort-upload", "upload_type", "multipart", "session_token", token), + null); + } catch (Exception e) { + LOG.warn("Failed to abort upload: {}", e.toString()); + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + } + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtResponseRecorder.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtResponseRecorder.java new file mode 100644 index 000000000..a6c54103a --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtResponseRecorder.java @@ -0,0 +1,93 @@ +package com.databricks.sdk.mixin; + +import com.databricks.sdk.core.http.HttpClient; +import com.databricks.sdk.core.http.Request; +import com.databricks.sdk.core.http.Response; +import java.io.IOException; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Map; + +/** + * The HTTP client of the extension's single-attempt workspace API client: the configured client, + * unchanged, which also records what the response to each expected request said. The classic API + * client keeps no response on the error it throws, and the retry loop needs the response's + * Retry-After, as a download needs the status of a success. + * + *

Answers are kept by request identity, which holds because the API client hands the caller's + * own {@link Request} to its HTTP client. Only expected requests are recorded, and their callers + * forget them in a {@code finally}, so nothing outlives its call. + */ +final class FilesExtResponseRecorder implements HttpClient { + /** What a workspace response said that its error does not. */ + static final class Answer { + final int statusCode; + + /** The wait the server asked for, or null when it asks for none. */ + final Long retryAfterSeconds; + + Answer(int statusCode, Long retryAfterSeconds) { + this.statusCode = statusCode; + this.retryAfterSeconds = retryAfterSeconds; + } + } + + /** The answer of an expected request that has none yet. */ + private static final Answer NONE = new Answer(0, null); + + private final HttpClient delegate; + + private final Map answers = Collections.synchronizedMap(new IdentityHashMap<>()); + + FilesExtResponseRecorder(HttpClient delegate) { + this.delegate = delegate; + } + + @Override + public Response execute(Request in) throws IOException { + Response response = delegate.execute(in); + answers.replace(in, NONE, new Answer(response.getStatusCode(), retryAfterSeconds(response))); + return response; + } + + /** Records the answer to {@code request} when it comes; {@link #forget} it once done. */ + void expect(Request request) { + answers.put(request, NONE); + } + + /** The answer to an expected request, or null if no response came back. */ + Answer answerTo(Request request) { + Answer answer = answers.get(request); + return answer == NONE ? null : answer; + } + + void forget(Request request) { + answers.remove(request); + } + + /** How many requests are expected or answered and not yet forgotten. */ + int pending() { + return answers.size(); + } + + /** + * The Retry-After of a 429 or 503: the header's integer seconds, or 1 when it is missing or not + * an integer. HTTP dates are not parsed, so a wait does not depend on the client's clock. Other + * responses ask for no wait. + */ + static Long retryAfterSeconds(Response response) { + int status = response.getStatusCode(); + if (status != 429 && status != 503) { + return null; + } + String header = response.getFirstHeader("Retry-After"); + if (header == null) { + return FilesExtRetry.DEFAULT_RETRY_AFTER_SECONDS; + } + try { + return Long.parseLong(header.trim()); + } catch (NumberFormatException e) { + return FilesExtRetry.DEFAULT_RETRY_AFTER_SECONDS; + } + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtRetry.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtRetry.java new file mode 100644 index 000000000..4da828625 --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtRetry.java @@ -0,0 +1,545 @@ +package com.databricks.sdk.mixin; + +import com.databricks.sdk.core.ApiClient; +import com.databricks.sdk.core.DatabricksError; +import com.databricks.sdk.core.DatabricksException; +import com.databricks.sdk.core.error.platform.AlreadyExists; +import com.databricks.sdk.core.http.Request; +import com.databricks.sdk.core.logging.Logger; +import com.databricks.sdk.core.logging.LoggerFactory; +import com.databricks.sdk.core.retry.RetryUtils; +import com.databricks.sdk.core.utils.Timer; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.time.Duration; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; +import java.util.function.BooleanSupplier; +import java.util.function.Function; +import org.apache.http.ConnectionClosedException; +import org.apache.http.MalformedChunkCodingException; +import org.apache.http.TruncatedChunkException; + +/** + * The retry loop and the endpoint walk that every client of the Files transfer extension shares: + * what a failure means (retry on this endpoint, walk to the next one, or raise), how long to keep + * retrying, and when a transfer may move to the next endpoint. + * + *

Errors surface as the classic SDK's own: an I/O failure as {@code DatabricksError("IO_ERROR", + * 523, cause)}, as {@link com.databricks.sdk.core.ApiClient} reports it, and a spent budget as a + * {@link DatabricksException} whose cause is the last failure, as its retries end. + */ +final class FilesExtRetry { + private static final Logger LOG = LoggerFactory.getLogger(FilesExtRetry.class); + + private FilesExtRetry() {} + + /** What a failed request means for the transfer. */ + enum Decision { + /** Send it again on this endpoint. */ + RETRY, + /** Give up on this endpoint; the next one may take the transfer. */ + WALK, + /** Fail the transfer: every endpoint would fail it the same way. */ + RAISE + } + + /** A failure an endpoint client hands back: what the walk should do with it. */ + static final class Failure { + /** Thrown as is at the public API. */ + final RuntimeException error; + + /** {@link Decision#WALK} or {@link Decision#RAISE}; retries already happened in the client. */ + final Decision decision; + + Failure(RuntimeException error, Decision decision) { + this.error = error; + this.decision = decision; + } + } + + /** How often and how long a request may be retried. */ + static final class Budget { + /** Null for no cap on attempts. */ + final Integer maxAttempts; + + final Duration timeout; + + /** Null for no cap; used by downloads that resume after a break. */ + final Integer maxRetriesWithoutProgress; + + Budget(Integer maxAttempts, Duration timeout) { + this(maxAttempts, timeout, null); + } + + Budget(Integer maxAttempts, Duration timeout, Integer maxRetriesWithoutProgress) { + this.maxAttempts = maxAttempts; + this.timeout = timeout; + this.maxRetriesWithoutProgress = maxRetriesWithoutProgress; + } + } + + /** + * One transfer on one endpoint, shared by every thread of that transfer. Only the walk side sets + * it; clients only read it. Both flags are only ever set, never cleared. + */ + static final class TransferStatus { + private volatile boolean committed; + private volatile boolean cancelled; + + /** No endpoint is left to walk to, so a failure before commit is retried instead of walked. */ + final boolean isLastEndpoint; + + /** How often a request is retried before commit when another endpoint is left. */ + final int retriesBeforeCommit; + + TransferStatus(boolean isLastEndpoint, int retriesBeforeCommit) { + this.isLastEndpoint = isLastEndpoint; + this.retriesBeforeCommit = retriesBeforeCommit; + } + + /** Set on the first acknowledged byte: from then on the transfer cannot move endpoints. */ + void commit() { + committed = true; + } + + /** Set on the first failure of a parallel transfer, so no new request starts. */ + void cancel() { + cancelled = true; + } + + boolean committed() { + return committed; + } + + boolean cancelled() { + return cancelled; + } + } + + /** + * A failed request inside an endpoint client: the error to surface, and what deciding needs to + * know about it. + */ + static final class RequestFailed extends Exception { + final RuntimeException error; + + /** Null if no response came back. */ + final Integer statusCode; + + /** Null to let the decision rules decide. */ + final Decision decision; + + /** The response's Retry-After, or null without one. */ + final Long retryAfterSeconds; + + RequestFailed(RuntimeException error, Integer statusCode, Decision decision) { + this(error, statusCode, decision, null); + } + + RequestFailed( + RuntimeException error, Integer statusCode, Decision decision, Long retryAfterSeconds) { + super(error.getMessage(), error); + this.error = error; + this.statusCode = statusCode; + this.decision = decision; + this.retryAfterSeconds = retryAfterSeconds; + } + } + + /** + * Reading the data to upload failed, not the connection. Clients wrap the user's source in it, so + * that a local I/O failure is not retried as a dropped connection would be. + */ + static final class SourceReadFailed extends IOException { + SourceReadFailed(IOException cause) { + super("Reading the data to upload failed: " + cause.getMessage(), cause); + } + } + + /** A presigned URL was answered with the cloud's "URL expired" error. */ + static final class UrlExpired extends RuntimeException { + UrlExpired(String message) { + super(message); + } + } + + /** An endpoint client, named in the walk's log. */ + interface EndpointClient { + String name(); + } + + /** One request, which may fail with any exception. */ + interface Send { + T send() throws Exception; + } + + /** One attempt of a transfer on one endpoint client: null on success, else its failure. */ + interface AttemptOnEndpoint { + Failure attempt(C client, TransferStatus status); + } + + /** The value a retried request returned, or the failure it ended with. */ + static final class Result { + final T value; + final Failure failure; + + private Result(T value, Failure failure) { + this.value = value; + this.failure = failure; + } + + static Result of(T value) { + return new Result<>(value, null); + } + + static Result failed(Failure failure) { + return new Result<>(null, failure); + } + + boolean failed() { + return failure != null; + } + } + + static final Set RETRYABLE_STATUS_CODES = + Collections.unmodifiableSet(new HashSet<>(Arrays.asList(408, 429, 502, 503, 504))); + + /** The longest wait between two attempts without Retry-After, in seconds. */ + static final int MAX_BACKOFF_SECONDS = 10; + + /** The wait after a 429 or 503 that has no Retry-After, in seconds. */ + static final long DEFAULT_RETRY_AFTER_SECONDS = 1; + + /** + * Messages of errors that are retried whatever their status, beyond those {@link + * RetryUtils#isCausedByTransientError} already matches: the server reports these for conditions + * that clear on their own. + */ + private static final List MORE_TRANSIENT_ERROR_MESSAGES = + Arrays.asList( + "Unexpected error", + "Please try again later or try a faster operation.", + "RPC token bucket limit has been exceeded"); + + /** The error a failure surfaces as. */ + static RuntimeException unwrap(Exception failure) { + if (failure instanceof RequestFailed) { + return ((RequestFailed) failure).error; + } + if (failure instanceof IOException) { + return new DatabricksError("IO_ERROR", 523, failure); + } + if (failure instanceof RuntimeException) { + return (RuntimeException) failure; + } + return new DatabricksException(failure.getMessage(), failure); + } + + /** + * The API client's rules: a throttled response, a dropped connection or a timeout is retried. + * Anything else walks, as no rule says it is certain to fail everywhere. + */ + static Decision apiClientDecision(Exception failure) { + if (failure instanceof RequestFailed && ((RequestFailed) failure).decision != null) { + return ((RequestFailed) failure).decision; + } + RuntimeException error = unwrap(failure); + if (error instanceof AlreadyExists) { + return Decision.RAISE; + } + if (retryAfterSeconds(failure) != null || isRetryable(error)) { + return Decision.RETRY; + } + if (!(error instanceof DatabricksError + || error instanceof IllegalArgumentException + || error instanceof UncheckedIOException + || error instanceof UrlExpired)) { + LOG.warn("Unexpected error, trying the next endpoint: {}", error.toString(), error); + } + return Decision.WALK; + } + + /** + * The rows every endpoint shares: 408, 429, 502, 503 and 504 responses are retried, a 412 raises, + * then the API client's rules. + */ + static Decision commonDecision(Exception failure) { + if (failure instanceof RequestFailed && ((RequestFailed) failure).decision == null) { + Integer status = ((RequestFailed) failure).statusCode; + if (status != null && RETRYABLE_STATUS_CODES.contains(status)) { + return Decision.RETRY; + } + if (status != null && status == 412) { + // The file no longer matches the request's precondition, on every endpoint. + return Decision.RAISE; + } + } + return apiClientDecision(failure); + } + + /** + * How long the server asked to wait, or null. Workspace calls get the response's Retry-After + * through {@link #onWorkspace}. A 429 or 503 the classic API client threw outside it has no + * response, so it waits {@link #DEFAULT_RETRY_AFTER_SECONDS}, as for a missing Retry-After. + */ + static Long retryAfterSeconds(Exception failure) { + if (failure instanceof RequestFailed) { + // What its client read from the response: a cloud error has none, so it backs off. + return ((RequestFailed) failure).retryAfterSeconds; + } + RuntimeException error = unwrap(failure); + if (error instanceof DatabricksError) { + int status = ((DatabricksError) error).getStatusCode(); + if (status == 429 || status == 503) { + return DEFAULT_RETRY_AFTER_SECONDS; + } + } + return null; + } + + /** + * The retryable errors: a failed connection or a timeout, or a message known to be transient. A + * response body cut off mid-read is not one of them, nor is a failure to read the data to upload. + */ + static boolean isRetryable(RuntimeException error) { + if (!(error instanceof DatabricksError)) { + return false; + } + Throwable cause = error.getCause(); + if (cause instanceof IOException) { + return !(cause instanceof SourceReadFailed) && !isBrokenBody((IOException) cause); + } + if (RetryUtils.isCausedByTransientError((DatabricksError) error)) { + return true; + } + String message = error.getMessage(); + if (message != null) { + for (String transient_ : MORE_TRANSIENT_ERROR_MESSAGES) { + if (message.contains(transient_)) { + return true; + } + } + } + return false; + } + + /** Whether the body of a response was cut off before its declared end. */ + static boolean isBrokenBody(IOException e) { + return e instanceof ConnectionClosedException + || e instanceof TruncatedChunkException + || e instanceof MalformedChunkCodingException; + } + + /** + * The error the classic SDK's retries end with once the budget is spent: a {@link + * DatabricksException} whose cause is the last failure. + */ + static DatabricksException exhaustedError(Budget budget, int attempts, RuntimeException last) { + if (budget.maxAttempts != null && attempts > budget.maxAttempts) { + return new DatabricksException( + "Exceeded max retry attempts (" + budget.maxAttempts + ")", last); + } + return new DatabricksException("Timed out after " + budget.timeout, last); + } + + /** Waits, waking early once the transfer is cancelled. */ + static void sleep(Timer clock, long millis, TransferStatus status) { + long remaining = millis; + while (remaining > 0 && !status.cancelled()) { + long step = Math.min(remaining, 1000); + try { + clock.sleep(step); + } catch (InterruptedException e) { + throw interrupted(e); + } + remaining -= step; + } + } + + /** What the classic API client throws when its thread is interrupted. */ + private static DatabricksException interrupted(InterruptedException e) { + Thread.currentThread().interrupt(); + return new DatabricksException("Current thread was interrupted", e); + } + + /** A workspace call's value, and the status of the response it came from. */ + static final class Answered { + final T value; + final int statusCode; + + Answered(T value, int statusCode) { + this.value = value; + this.statusCode = statusCode; + } + } + + /** + * Sends one workspace request through the single-attempt API client: an error response becomes a + * {@link RequestFailed} with its status code and Retry-After, and a request that got no response + * fails with its own error. The recorded answer is forgotten on every path. + */ + static Answered onWorkspace( + ApiClient workspace, FilesExtResponseRecorder responses, Request request, Class type) + throws IOException, RequestFailed { + responses.expect(request); + try { + T value = workspace.execute(request, type); + FilesExtResponseRecorder.Answer answer = responses.answerTo(request); + return new Answered<>(value, answer == null ? 200 : answer.statusCode); + } catch (DatabricksError e) { + FilesExtResponseRecorder.Answer answer = responses.answerTo(request); + if (answer == null) { + // No response came back, as for a failure before the request was sent. + throw e; + } + // The response's own status: a typed error carries its class's canonical one, as for a 412 + // whose body says UNKNOWN. + throw new RequestFailed(e, answer.statusCode, null, answer.retryAfterSeconds); + } finally { + responses.forget(request); + } + } + + static Result retry( + Send send, + Function decide, + Budget budget, + TransferStatus status, + Timer clock) { + return retry(send, decide, budget, status, clock, null, null); + } + + /** + * The one retry loop, which every client calls. Sends until it succeeds, until {@code decide} + * says walk or raise, until the budget is spent (then walks), or until the transfer is cancelled. + * Before commit it retries only {@code status.retriesBeforeCommit} times, unless this is the last + * endpoint: walking is cheaper than waiting. Waits min(10, attempt) seconds plus up to a second + * of jitter, or Retry-After; the wait ends early if the transfer is cancelled. + * + * @param beforeRetry runs before each wait, or null + * @param canRetry whether the request can be sent again, or null if it always can + */ + static Result retry( + Send send, + Function decide, + Budget budget, + TransferStatus status, + Timer clock, + Runnable beforeRetry, + BooleanSupplier canRetry) { + long deadline = clock.getCurrentTime() + budget.timeout.toMillis(); + int attempt = 1; + Exception last = null; + RuntimeException lastError = null; + while (clock.getCurrentTime() < deadline + && (budget.maxAttempts == null || attempt <= budget.maxAttempts)) { + try { + return Result.of(send.send()); + } catch (InterruptedException e) { + throw interrupted(e); + } catch (Exception e) { + last = e; + lastError = unwrap(e); + } + if (Thread.currentThread().isInterrupted()) { + // The caller is stopping the transfer: neither retry nor walk, as the API client would not. + throw new DatabricksException("Current thread was interrupted", lastError); + } + Decision decision = decide.apply(last); + if (decision != Decision.RETRY) { + return Result.failed(new Failure(lastError, decision)); + } + if (status.cancelled() + || (!(status.committed() || status.isLastEndpoint) + && attempt > status.retriesBeforeCommit) + || (canRetry != null && !canRetry.getAsBoolean())) { + return Result.failed(new Failure(lastError, Decision.WALK)); + } + if (budget.maxAttempts != null && attempt >= budget.maxAttempts) { + attempt++; + break; + } + long waitMillis = waitMillis(retryAfterSeconds(last), attempt); + if (waitMillis >= deadline - clock.getCurrentTime()) { + // A wait that would outlast the budget ends the same way, without holding the thread. + attempt++; + break; + } + LOG.debug("Retrying after {} (sleeping {}ms)", lastError, waitMillis); + if (beforeRetry != null) { + beforeRetry.run(); + } + sleep(clock, waitMillis, status); + if (status.cancelled()) { + return Result.failed(new Failure(lastError, Decision.WALK)); + } + attempt++; + } + return Result.failed(new Failure(exhaustedError(budget, attempt, lastError), Decision.WALK)); + } + + /** + * The wait before the next attempt: the server's Retry-After, never negative, or min(10, attempt) + * seconds; plus up to a second of jitter. Saturates rather than overflows on a huge Retry-After. + */ + static long waitMillis(Long retryAfterSeconds, int attempt) { + long seconds = + retryAfterSeconds != null + ? Math.min(Math.max(retryAfterSeconds, 0L), Long.MAX_VALUE / 1000 - 1) + : Math.min(MAX_BACKOFF_SECONDS, attempt); + return seconds * 1000 + ThreadLocalRandom.current().nextLong(1000); + } + + /** The one walk rule, shared by the endpoint walk and the walking download stream. */ + static boolean mayWalk( + Failure failure, + TransferStatus status, + boolean hasNextEndpoint, + BooleanSupplier canSendAgain) { + return failure.decision == Decision.WALK + && !status.committed() + && hasNextEndpoint + && canSendAgain.getAsBoolean(); + } + + static void walkEndpoints( + List clients, AttemptOnEndpoint attempt) { + walkEndpoints(clients, attempt, () -> true, () -> {}, 0); + } + + /** + * Runs the transfer on each client in order, each with a new {@link TransferStatus}, and returns + * once one succeeds. Moves on only if the failure walks, the transfer is not committed, and the + * data can be sent again; otherwise throws the failure's error. + */ + static void walkEndpoints( + List clients, + AttemptOnEndpoint attempt, + BooleanSupplier canSendAgain, + Runnable beforeNextEndpoint, + int retriesBeforeCommit) { + for (int index = 0; index < clients.size(); index++) { + C client = clients.get(index); + boolean isLast = index + 1 == clients.size(); + TransferStatus status = new TransferStatus(isLast, retriesBeforeCommit); + Failure failure = attempt.attempt(client, status); + if (failure == null) { + return; + } + if (!mayWalk(failure, status, !isLast, canSendAgain)) { + throw failure.error; + } + LOG.info( + "{} failed before commit, trying the next endpoint: {}", + client.name(), + failure.error.toString()); + beforeNextEndpoint.run(); + } + throw new IllegalArgumentException("No endpoint can take this transfer"); + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtUploadData.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtUploadData.java new file mode 100644 index 000000000..5c0220b86 --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtUploadData.java @@ -0,0 +1,412 @@ +package com.databricks.sdk.mixin; + +import com.databricks.sdk.mixin.FilesExtRetry.SourceReadFailed; +import java.io.ByteArrayInputStream; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.SequenceInputStream; +import java.nio.ByteBuffer; +import java.nio.channels.ClosedByInterruptException; +import java.nio.channels.FileChannel; +import java.nio.channels.SeekableByteChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.util.Arrays; + +/** + * The bytes being uploaded, and whether they can be sent again from the start. They come from a + * file, a seekable channel (uploaded from its position when given), or a one-pass stream. + * + *

A one-pass stream keeps every byte read until the upload is committed, so the next endpoint + * can be sent the same bytes. A multipart upload limits that to the first part. + * + *

A failure to read the source is a {@link SourceReadFailed}, so the retry rules do not take it + * for a dropped connection. Every method is thread-safe; the body stream {@link #whole} returns is + * read by one request at a time. + * + *

A file or channel is read with the thread's interrupt status cleared and then restored: an + * interrupted read closes a {@link FileChannel} for every thread, which would close the caller's + * channel or fail every later read. An interrupt that still lands mid-read reopens a file this + * opened; the caller's channel can't be reopened, so that read fails. + */ +final class FilesExtUploadData implements AutoCloseable { + /** One part of a multipart upload: its number, from 1, and its bytes. */ + static final class Part { + final int number; + final byte[] data; + + Part(int number, byte[] data) { + this.number = number; + this.data = data; + } + } + + /** The first buffer of a one-pass read, grown as bytes arrive. */ + private static final int STREAM_CHUNK = 1024 * 1024; + + /** The largest Java array, and so the most a one-pass stream can keep for a replay. */ + private static final int MAX_KEPT_BYTES = Integer.MAX_VALUE - 8; + + private final Path pathOrNull; + private SeekableByteChannel channelOrNull; + private final InputStream streamOrNull; + private final boolean ownsChannel; + + /** The channel position the data starts at; a file starts at 0. */ + private final long start; + + /** Rewindable sources only: the channel position of the next byte to hand out. */ + private long channelOffset; + + private Long sizeOrNull; + private int partNumber; + + // One-pass streams only: the bytes kept for a replay (replay[0, replayLength)), the offset of + // their first byte, the offset of the next byte to hand out, whether bytes read from now on are + // kept, whether the stream ended, and whether bytes were handed out without being kept. + private byte[] replay = new byte[0]; + private int replayLength; + private long replayStart; + private long position; + private boolean retaining = true; + private boolean eof; + private boolean lost; + private long streamBytesRead; + + private FilesExtUploadData( + Path pathOrNull, + SeekableByteChannel channelOrNull, + InputStream streamOrNull, + long start, + Long sizeOrNull) { + this.pathOrNull = pathOrNull; + this.channelOrNull = channelOrNull; + this.streamOrNull = streamOrNull; + this.ownsChannel = pathOrNull != null; + this.start = start; + this.channelOffset = start; + this.sizeOrNull = sizeOrNull; + } + + /** The file at {@code path}; opened on the first read, closed by {@link #close}. */ + static FilesExtUploadData fromFile(Path path) throws IOException { + return new FilesExtUploadData(path, null, null, 0, Files.size(path)); + } + + /** The channel's bytes from its position. The caller keeps the channel open and closes it. */ + static FilesExtUploadData fromChannel(SeekableByteChannel channel) throws IOException { + long start = channel.position(); + return new FilesExtUploadData(null, channel, null, start, Math.max(0, channel.size() - start)); + } + + /** A one-pass stream, whose size is known once it ends. The caller closes the stream. */ + static FilesExtUploadData fromStream(InputStream stream) { + return new FilesExtUploadData(null, null, stream, 0, null); + } + + /** The size in bytes, or null while a one-pass stream has not ended. */ + synchronized Long sizeOrNull() { + return sizeOrNull; + } + + private boolean rewindable() { + return streamOrNull == null; + } + + /** What runs on the channel, positioned by the caller. */ + private interface ChannelRead { + T run(SeekableByteChannel channel) throws IOException; + } + + /** + * Runs {@code read} on the source channel with the interrupt status cleared, then restores it. A + * file this opened that an interrupt closed anyway is reopened, once. Any I/O failure is a {@link + * SourceReadFailed}. + */ + private T withoutInterrupt(ChannelRead read) throws IOException { + boolean interrupted = Thread.interrupted(); + try { + for (int attempt = 0; ; attempt++) { + try { + if (channelOrNull == null) { + channelOrNull = FileChannel.open(pathOrNull, StandardOpenOption.READ); + } + return read.run(channelOrNull); + } catch (ClosedByInterruptException e) { + // Clear the interrupt for the reopened read; it is restored below. + Thread.interrupted(); + interrupted = true; + if (!ownsChannel || attempt > 0) { + throw new SourceReadFailed(e); + } + channelOrNull = null; + } + } + } catch (SourceReadFailed e) { + throw e; + } catch (IOException e) { + throw new SourceReadFailed(e); + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + } + + /** Reads into b[off, off + len) from {@code offset} until full or the end: the count, or -1. */ + private static int fill(SeekableByteChannel channel, long offset, byte[] b, int off, int len) + throws IOException { + channel.position(offset); + ByteBuffer buffer = ByteBuffer.wrap(b, off, len); + while (buffer.hasRemaining()) { + int read = channel.read(buffer); + if (read < 0) { + break; + } + if (read == 0) { + // Only a non-blocking channel reads nothing with space left; waiting would spin. + throw new IOException( + "The channel returned no bytes: a non-blocking channel can't be uploaded"); + } + } + int read = buffer.position() - off; + return read == 0 && len > 0 ? -1 : read; + } + + /** Reads n bytes from a rewindable source, or fewer only at its end. */ + private byte[] readChannel(int n) throws IOException { + byte[] out = + withoutInterrupt( + channel -> { + // Never more than is left, so a short tail doesn't allocate a whole part. + long left = Math.max(0, channel.size() - channelOffset); + byte[] data = new byte[(int) Math.min(n, left)]; + int read = Math.max(0, fill(channel, channelOffset, data, 0, data.length)); + return read == data.length ? data : Arrays.copyOf(data, read); + }); + channelOffset += out.length; + return out; + } + + /** + * Reads n bytes from the one-pass stream, or fewer only at its end: a stream may return less than + * asked before it ends. The buffer grows as bytes arrive, so a short stream doesn't allocate n. + */ + private byte[] readStream(int n) throws IOException { + byte[] data = new byte[Math.min(n, STREAM_CHUNK)]; + int read = 0; + try { + while (read < n) { + if (read == data.length) { + data = Arrays.copyOf(data, (int) Math.min(n, 2L * data.length)); + } + int more = streamOrNull.read(data, read, data.length - read); + if (more < 0) { + eof = true; + break; + } + read += more; + } + } catch (IOException e) { + if (read > 0) { + // The bytes read before the failure are gone from the stream, so it can't start over. + lost = true; + } + throw new SourceReadFailed(e); + } + streamBytesRead += read; + if (eof) { + sizeOrNull = streamBytesRead; + } + return read == data.length ? data : Arrays.copyOf(data, read); + } + + private void keep(byte[] more) { + long needed = (long) replayLength + more.length; + if (needed > MAX_KEPT_BYTES) { + // Uploads keep at most one part (1 GiB) or the single-shot threshold before commit. + throw new IllegalStateException( + "A one-pass upload kept more than " + MAX_KEPT_BYTES + " bytes"); + } + if (needed > replay.length) { + replay = + Arrays.copyOf( + replay, (int) Math.max(needed, Math.min(MAX_KEPT_BYTES, 2L * replay.length))); + } + System.arraycopy(more, 0, replay, replayLength, more.length); + replayLength += more.length; + } + + /** + * Reads up to n bytes of a one-pass stream ahead and keeps them for {@link #read}, so a shorter + * stream learns its size. A file or channel knows its size already. + */ + synchronized void readAhead(int n) throws IOException { + if (rewindable()) { + return; + } + long available = replayStart + replayLength - position; + if (available < n && !eof) { + keep(readStream((int) (n - available))); + } + } + + /** The next n bytes, or fewer only at the end. */ + synchronized byte[] read(int n) throws IOException { + if (rewindable()) { + return readChannel(n); + } + // Past the kept bytes once bytes are handed out without being kept, after commit. + int from = (int) Math.min(position - replayStart, replayLength); + byte[] out = Arrays.copyOfRange(replay, from, from + Math.min(n, replayLength - from)); + if (out.length < n && !eof) { + byte[] more = readStream(n - out.length); + if (retaining) { + keep(more); + } else if (more.length > 0) { + lost = true; + } + if (out.length == 0) { + out = more; + } else { + byte[] joined = Arrays.copyOf(out, out.length + more.length); + System.arraycopy(more, 0, joined, out.length, more.length); + out = joined; + } + } + position += out.length; + return out; + } + + /** The next part, or null at the end. */ + synchronized Part nextPart(int size) throws IOException { + byte[] data = read(size); + if (data.length == 0) { + return null; + } + partNumber++; + return new Part(partNumber, data); + } + + /** + * The data for a single-shot PUT, from the start. The caller may close the stream; that leaves + * the source open. A failure to read the source is a {@link SourceReadFailed}. + */ + synchronized InputStream whole() throws IOException { + if (rewindable()) { + return new ChannelBody(); + } + if (eof && replayStart == 0 && !lost) { + // Nothing writes to these kept bytes again: the stream has ended. + return new ByteArrayInputStream(replay, 0, replayLength); + } + // The rest is streamed and can't be read again. + lost = true; + int from = (int) Math.min(position - replayStart, replayLength); + return new SequenceInputStream( + new ByteArrayInputStream(Arrays.copyOfRange(replay, from, replayLength)), + new SourceStream(streamOrNull)); + } + + /** How many bytes of a one-pass stream are kept for a replay. */ + synchronized int keptBytes() { + return replayLength; + } + + synchronized boolean canSendAgain() { + return rewindable() || (replayStart == 0 && !lost); + } + + /** Starts over from the first byte, if {@link #canSendAgain}, and from part 1. */ + synchronized void restart() { + partNumber = 0; + if (rewindable()) { + channelOffset = start; + } else if (canSendAgain()) { + position = 0; + } + } + + /** Called at commit: nothing will be sent again from the start. */ + synchronized void dropReplayBuffer() { + if (rewindable()) { + return; + } + int from = (int) Math.min(position - replayStart, replayLength); + replay = Arrays.copyOfRange(replay, from, replayLength); + replayLength -= from; + replayStart = position; + retaining = false; + } + + /** Closes the file this opened; a channel or stream the caller passed stays open. */ + @Override + public synchronized void close() throws IOException { + if (ownsChannel && channelOrNull != null) { + channelOrNull.close(); + channelOrNull = null; + } + } + + /** + * A file or channel from the start, as a request body, read as {@link #readChannel} reads. + * Closing it leaves the source open. + */ + private final class ChannelBody extends InputStream { + private long offset = start; + + @Override + public int read() throws IOException { + byte[] one = new byte[1]; + int n = read(one, 0, 1); + return n < 0 ? -1 : one[0] & 0xff; + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + if (len == 0) { + return 0; + } + synchronized (FilesExtUploadData.this) { + int read = withoutInterrupt(channel -> fill(channel, offset, b, off, len)); + if (read > 0) { + offset += read; + } + return read; + } + } + } + + /** + * The source as a request body: a read failure is a {@link SourceReadFailed}, and closing it + * leaves the source open, as the upload owns neither the user's stream nor a file it reopens. + */ + private static final class SourceStream extends FilterInputStream { + SourceStream(InputStream in) { + super(in); + } + + @Override + public int read() throws IOException { + try { + return super.read(); + } catch (IOException e) { + throw e instanceof SourceReadFailed ? e : new SourceReadFailed(e); + } + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + try { + return super.read(b, off, len); + } catch (IOException e) { + throw e instanceof SourceReadFailed ? e : new SourceReadFailed(e); + } + } + + @Override + public void close() {} + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtUploadPlan.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtUploadPlan.java new file mode 100644 index 000000000..6f94074d3 --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtUploadPlan.java @@ -0,0 +1,163 @@ +package com.databricks.sdk.mixin; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * How an upload is sent to one endpoint, and the policy that picks it. The policy's defaults are + * internal tunables. + * + *

A multipart upload opens a session with parts of {@link #partSize} bytes on up to {@link + * #parallelism} threads, and asks for their presigned URLs {@link #batchSize} at a time. Otherwise + * the whole file goes in one PUT. + */ +final class FilesExtUploadPlan { + private static final int MIB = 1024 * 1024; + + /** The part size for data of unknown size. */ + static final int DEFAULT_PART_SIZE = 10 * MIB; + + /** + * The part sizes the policy picks from: the smallest giving at most {@link #TARGET_PART_COUNT} + * parts. A part is held in one byte array, which can't reach 2 GiB, so the largest part is 1 GiB. + */ + static final List PART_SIZE_OPTIONS = + Collections.unmodifiableList( + Arrays.asList(10 * MIB, 20 * MIB, 50 * MIB, 100 * MIB, 200 * MIB, 500 * MIB, 1024 * MIB)); + + /** The largest part, picked or given; see {@link #PART_SIZE_OPTIONS}. */ + static final int MAX_PART_SIZE = 1024 * MIB; + + /** Data smaller than this goes in a single shot. A one-pass stream is read this far ahead. */ + static final int MIN_MULTIPART_SIZE = 50 * MIB; + + /** How many presigned part URLs to ask for at a time when the size is unknown. */ + static final int DEFAULT_BATCH_SIZE = 1; + + static final int DEFAULT_PARALLELISM = 10; + + static final int TARGET_PART_COUNT = 100; + + /** What an endpoint client can take, as the planning sees it. */ + interface UploadCapabilities { + boolean supportsMultipart(); + + boolean supportsSingleShot(); + + /** The largest single-request upload, or null for no limit. */ + Long maxSingleShotSizeOrNull(); + + /** The largest part, or null for no limit. */ + Long maxPartSizeOrNull(); + } + + /** The part size and presigned-URL batch size for data of a given size. */ + static final class PartSizing { + final int partSize; + final int batchSize; + + PartSizing(int partSize, int batchSize) { + this.partSize = partSize; + this.batchSize = batchSize; + } + } + + final boolean multipart; + final int partSize; + final int parallelism; + final int batchSize; + + FilesExtUploadPlan(boolean multipart, int partSize, int parallelism, int batchSize) { + this.multipart = multipart; + this.partSize = partSize; + this.parallelism = parallelism; + this.batchSize = batchSize; + } + + /** + * The part size: the one given, or the smallest option that gives at most {@link + * #TARGET_PART_COUNT} parts (the largest if none does), or {@link #DEFAULT_PART_SIZE} for data of + * unknown size. The batch size is the square root of the part count, rounded up, or {@link + * #DEFAULT_BATCH_SIZE} for data of unknown size. + * + * @throws IllegalArgumentException if the given part size is not positive or exceeds {@link + * #MAX_PART_SIZE} + */ + static PartSizing partSizing(Long sizeOrNull, Integer partSizeOrNull) { + int partSize; + if (partSizeOrNull != null) { + if (partSizeOrNull <= 0) { + throw new IllegalArgumentException("Part size " + partSizeOrNull + " must be positive."); + } + if (partSizeOrNull > MAX_PART_SIZE) { + throw new IllegalArgumentException( + "Part size " + + partSizeOrNull + + " exceeds maximum allowed size " + + MAX_PART_SIZE + + " bytes."); + } + partSize = partSizeOrNull; + } else if (sizeOrNull != null) { + partSize = MAX_PART_SIZE; + for (int option : PART_SIZE_OPTIONS) { + if (partCount(sizeOrNull, option) <= TARGET_PART_COUNT) { + partSize = option; + break; + } + } + } else { + partSize = DEFAULT_PART_SIZE; + } + int batchSize = + sizeOrNull == null + ? DEFAULT_BATCH_SIZE + : (int) Math.ceil(Math.sqrt((double) partCount(sizeOrNull, partSize))); + return new PartSizing(partSize, batchSize); + } + + static long partCount(long size, int partSize) { + return (size + partSize - 1) / partSize; + } + + /** + * The plan for this data on this client, or null if the client can't take it: a single shot on a + * client without one, or data of known size over the client's single-request limit. + * + *

A single shot below {@code minMultipartSize}, for empty data (a multipart upload needs a + * part), or when the client has no multipart; the part size capped at the client's. Data of + * unknown size goes multipart, so a one-pass stream is read ahead first: a short one then knows + * its size. + */ + static FilesExtUploadPlan plan( + Long sizeOrNull, + UploadCapabilities client, + boolean useParallel, + Integer parallelismOrNull, + int partSize, + int batchSize, + int minMultipartSize) { + boolean small = sizeOrNull != null && sizeOrNull < Math.max(minMultipartSize, 1); + if (small || !client.supportsMultipart()) { + Long limit = client.maxSingleShotSizeOrNull(); + if (!client.supportsSingleShot() + || (limit != null && sizeOrNull != null && sizeOrNull > limit)) { + return null; + } + return new FilesExtUploadPlan(false, partSize, 1, 1); + } + Long maxPartSize = client.maxPartSizeOrNull(); + if (maxPartSize != null && maxPartSize < partSize) { + partSize = maxPartSize.intValue(); + } + if (useParallel) { + return new FilesExtUploadPlan( + true, + partSize, + parallelismOrNull == null || parallelismOrNull == 0 ? 1 : parallelismOrNull, + 1); + } + return new FilesExtUploadPlan(true, partSize, 1, batchSize); + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtUploadWalk.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtUploadWalk.java new file mode 100644 index 000000000..42fc5389c --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/mixin/FilesExtUploadWalk.java @@ -0,0 +1,407 @@ +package com.databricks.sdk.mixin; + +import com.databricks.sdk.core.DatabricksException; +import com.databricks.sdk.core.logging.Logger; +import com.databricks.sdk.core.logging.LoggerFactory; +import com.databricks.sdk.mixin.FilesExtRetry.Decision; +import com.databricks.sdk.mixin.FilesExtRetry.EndpointClient; +import com.databricks.sdk.mixin.FilesExtRetry.Failure; +import com.databricks.sdk.mixin.FilesExtRetry.Result; +import com.databricks.sdk.mixin.FilesExtRetry.TransferStatus; +import com.databricks.sdk.mixin.FilesExtUploadData.Part; +import com.databricks.sdk.mixin.FilesExtUploadPlan.UploadCapabilities; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * An upload over the endpoint walk: a plan per endpoint client, then a single shot or a multipart + * upload on each in turn until one succeeds. + * + *

A parallel upload runs on its own bounded pool of daemon threads, shut down before the call + * returns, so a call leaves no thread behind. An interrupt of the calling thread cancels the + * transfer without interrupting the workers: an interrupted read closes a file channel, which may + * be the caller's. Once they finish, it fails as the classic API client does. + */ +final class FilesExtUploadWalk { + private FilesExtUploadWalk() {} + + private static final Logger LOG = LoggerFactory.getLogger(FilesExtUploadWalk.class); + + /** The prefix of the names of the parallel transfer threads. */ + static final String TRANSFER_THREAD_NAME = "databricks-files-ext-transfer-"; + + /** + * The workspace, the usual fallback for uploads, takes single-shot uploads only, so a transient + * failure before commit is retried once before the upload moves there. + */ + static final int RETRIES_BEFORE_COMMIT = 1; + + /** An upload session on one endpoint. */ + interface MultipartSession { + /** Uploads one part: its ETag, or the failure. */ + Result putPart(int number, byte[] data, TransferStatus status); + + /** Completes the upload: null, or the failure. */ + Failure complete(Map etags, TransferStatus status); + + /** Sent once, never retried; a failure is only logged. */ + void abort(); + } + + /** An endpoint client that takes uploads. */ + interface UploadClient extends EndpointClient, UploadCapabilities { + /** Uploads the whole data in one request: null, or the failure. */ + Failure putFile( + String path, Boolean overwriteOrNull, FilesExtUploadData data, TransferStatus status); + + /** Opens a multipart upload session, asking for part URLs {@code batchSize} at a time. */ + Result initiateUpload( + String path, Boolean overwriteOrNull, TransferStatus status, int batchSize); + } + + /** The next item of a parallel transfer, or null at the end. */ + interface NextItem { + T next() throws IOException; + } + + /** The work on one item: null, or its failure. */ + interface Work { + Failure run(T item, TransferStatus status); + } + + /** + * Uploads the data to the first client that takes it, walking to the next before commit, and + * closes the data. + * + * @throws IllegalArgumentException if only single-request clients are left and the data is over + * their limit + */ + static void upload( + List clients, + FilesExtUploadData data, + String path, + Boolean overwriteOrNull, + int partSize, + int batchSize, + boolean useParallel, + Integer parallelismOrNull, + int minMultipartSize) + throws IOException { + try (FilesExtUploadData owned = data) { + if (data.sizeOrNull() == null) { + // A one-pass stream's size is only known once read: a short one is sent in a single shot. + data.readAhead(minMultipartSize); + } + Map plans = new LinkedHashMap<>(); + List tooLarge = new ArrayList<>(); + for (UploadClient client : clients) { + FilesExtUploadPlan plan = + FilesExtUploadPlan.plan( + data.sizeOrNull(), + client, + useParallel, + parallelismOrNull, + partSize, + batchSize, + minMultipartSize); + if (plan != null) { + plans.put(client, plan); + } else if (client.maxSingleShotSizeOrNull() != null) { + tooLarge.add(client.name()); + } + } + if (plans.isEmpty() && !tooLarge.isEmpty()) { + throw new IllegalArgumentException( + "No endpoint can take this upload of " + + data.sizeOrNull() + + " bytes: " + + String.join(", ", tooLarge) + + " takes a single request of at most 5 GiB, and no endpoint for multipart uploads" + + " is available"); + } + FilesExtRetry.walkEndpoints( + new ArrayList<>(plans.keySet()), + (client, status) -> + uploadTo(client, status, plans.get(client), path, overwriteOrNull, data), + data::canSendAgain, + data::restart, + RETRIES_BEFORE_COMMIT); + } + } + + /** + * Uploads the data to one endpoint with its plan. Marks the status committed on the first + * acknowledgment, and aborts the upload session once on any failure or exception. Never retries: + * the client does. + */ + static Failure uploadTo( + UploadClient client, + TransferStatus status, + FilesExtUploadPlan plan, + String path, + Boolean overwriteOrNull, + FilesExtUploadData data) { + if (!plan.multipart) { + Failure failure = client.putFile(path, overwriteOrNull, data, status); + if (failure == null) { + status.commit(); + } + return failure; + } + Result session = + client.initiateUpload(path, overwriteOrNull, status, plan.batchSize); + if (session.failed()) { + return session.failure; + } + Failure failure; + try { + failure = multipartUpload(session.value, data, plan, status); + } catch (RuntimeException | Error e) { + session.value.abort(); + throw e; + } + if (failure != null) { + session.value.abort(); + } + return failure; + } + + static Failure multipartUpload( + MultipartSession session, + FilesExtUploadData data, + FilesExtUploadPlan plan, + TransferStatus status) { + throwIfInterrupted(); + Part first = nextPart(data, plan.partSize); + if (first == null) { + // plan() sends empty data in a single shot. + throw new IllegalStateException("A multipart upload was planned for empty data"); + } + // The first part goes alone: its ETag is the commit point. + Result etag = session.putPart(first.number, first.data, status); + if (etag.failed()) { + return etag.failure; + } + status.commit(); + data.dropReplayBuffer(); + Map etags = new TreeMap<>(); + etags.put(first.number, etag.value); + Long size = data.sizeOrNull(); + int threads = + size == null + ? plan.parallelism + : (int) + Math.max( + 1, + Math.min( + plan.parallelism, FilesExtUploadPlan.partCount(size, plan.partSize) - 1)); + Failure failure = + runInParallel( + threads, + () -> data.nextPart(plan.partSize), + (part, partStatus) -> { + Result partEtag = session.putPart(part.number, part.data, partStatus); + if (partEtag.failed()) { + return partEtag.failure; + } + synchronized (etags) { + etags.put(part.number, partEtag.value); + } + return null; + }, + status); + if (failure != null) { + return failure; + } + return session.complete(etags, status); + } + + private static Part nextPart(FilesExtUploadData data, int size) { + try { + return data.nextPart(size); + } catch (IOException e) { + throw FilesExtRetry.unwrap(e); + } + } + + /** + * Runs {@code work} on up to {@code parallelism} threads until {@code next} returns null. {@code + * next} is called under a lock. The first failure cancels the status, so no new item starts, and + * is returned once every running item has finished. An exception from either becomes a walk + * failure. + * + *

With more than one thread, the threads are this call's own, and are gone when it returns. If + * the calling thread is interrupted, the transfer is cancelled, the call waits for the running + * items to finish, and throws {@code DatabricksException("Current thread was interrupted")} with + * the interrupt status set. + */ + static Failure runInParallel( + int parallelism, NextItem next, Work work, TransferStatus status) { + Object lock = new Object(); + List failures = new ArrayList<>(); + Runnable worker = + () -> { + while (true) { + // On the calling thread, an interrupt between successful parts stops the transfer too. + throwIfInterrupted(); + T item; + try { + synchronized (lock) { + if (status.cancelled()) { + return; + } + item = next.next(); + } + } catch (Exception e) { + rethrowIfInterrupted(e); + fail(lock, failures, new Failure(FilesExtRetry.unwrap(e), Decision.WALK), status); + return; + } + if (item == null) { + return; + } + Failure failure; + try { + failure = work.run(item, status); + } catch (Exception e) { + rethrowIfInterrupted(e); + LOG.warn("Unexpected error in a parallel transfer: {}", e.toString(), e); + failure = new Failure(FilesExtRetry.unwrap(e), Decision.WALK); + } + if (failure != null) { + fail(lock, failures, failure, status); + return; + } + } + }; + if (parallelism <= 1) { + worker.run(); + } else { + // An interrupt already pending starts no thread: no part starts after an interrupt. + throwIfInterrupted(); + runOnOwnThreads(parallelism, worker, status); + } + synchronized (lock) { + return failures.isEmpty() ? null : failures.get(0); + } + } + + /** + * On the calling thread (parallelism 1), an interrupt fails the transfer as the retry loop threw + * it, rather than walking: the caller asked to stop, so no other endpoint is tried. The workers + * of a parallel transfer are never interrupted. + */ + private static void throwIfInterrupted() { + if (Thread.currentThread().isInterrupted()) { + throw new DatabricksException("Current thread was interrupted", new InterruptedException()); + } + } + + private static void rethrowIfInterrupted(Exception e) { + if (Thread.currentThread().isInterrupted()) { + throw e instanceof RuntimeException + ? (RuntimeException) e + : new DatabricksException("Current thread was interrupted", e); + } + } + + private static void fail( + Object lock, List failures, Failure failure, TransferStatus status) { + synchronized (lock) { + if (failures.isEmpty()) { + failures.add(failure); + } else { + // The first failure decides; the others are only logged. + LOG.info("Another part of the transfer failed too: {}", failure.error.toString()); + } + status.cancel(); + } + } + + private static void runOnOwnThreads(int threads, Runnable worker, TransferStatus status) { + ExecutorService pool = Executors.newFixedThreadPool(threads, new TransferThreads()); + boolean interrupted = false; + Throwable thrown = null; + try { + List> running = new ArrayList<>(); + try { + for (int i = 0; i < threads; i++) { + running.add(pool.submit(worker)); + } + } catch (RuntimeException | Error e) { + // The threads already started stop at their next item. + status.cancel(); + throw e; + } + for (Future future : running) { + while (true) { + try { + future.get(); + break; + } catch (InterruptedException e) { + // Stop starting items; the running ones finish, so no worker is interrupted. + interrupted = true; + status.cancel(); + } catch (ExecutionException e) { + // Only an Error escapes the worker, which turns exceptions into failures. + if (thrown == null) { + thrown = e.getCause(); + } + status.cancel(); + break; + } + } + } + } finally { + pool.shutdown(); + while (true) { + try { + if (pool.awaitTermination(1, TimeUnit.MINUTES)) { + break; + } + } catch (InterruptedException e) { + interrupted = true; + status.cancel(); + } + } + } + // An interrupt that came once every part had finished still stops the transfer. + interrupted |= Thread.interrupted(); + if (thrown instanceof Error) { + if (interrupted) { + Thread.currentThread().interrupt(); + } + throw (Error) thrown; + } + if (interrupted) { + Thread.currentThread().interrupt(); + throw new DatabricksException("Current thread was interrupted", new InterruptedException()); + } + if (thrown != null) { + throw new DatabricksException(thrown.getMessage(), thrown); + } + } + + /** Daemon threads, so a transfer never keeps the JVM alive, named for thread dumps. */ + private static final class TransferThreads implements ThreadFactory { + private static final AtomicInteger COUNT = new AtomicInteger(); + + @Override + public Thread newThread(Runnable r) { + Thread thread = new Thread(r, TRANSFER_THREAD_NAME + COUNT.incrementAndGet()); + thread.setDaemon(true); + return thread; + } + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/aifunctions/AiDecideRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/aifunctions/AiDecideRequest.java index 05e620a00..78d9772e9 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/aifunctions/AiDecideRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/aifunctions/AiDecideRequest.java @@ -60,8 +60,9 @@ public class AiDecideRequest { /** * A nonempty array of typed content objects shared by all questions. Set `options.version` to - * `"2.0"` to use this format. Text and JSON content plus questions must fit within 32 KiB as - * compact UTF-8 JSON, excluding image parts. + * `"2.0"` to use this format. Each content object accepts only `type` and the content field + * listed below; other fields are rejected. Text and JSON content plus questions must fit within + * 32 KiB as compact UTF-8 JSON, excluding image parts. * *

| type | Content field | Value | | --- | --- | --- | | `text` | `text` | A nonblank string. * | | `json` | `data` | A JSON object or array. | | `image` | `image_url` | An inline base64 PNG diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AppPermissionLevel.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AppPermissionLevel.java index 5b2b07c9b..fa851a819 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AppPermissionLevel.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AppPermissionLevel.java @@ -7,6 +7,7 @@ /** Permission level */ @Generated public enum AppPermissionLevel { + CAN_BUILD, CAN_MANAGE, CAN_USE, } diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AppThumbnail.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AppThumbnail.java index ef06affcc..1f2835fb3 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AppThumbnail.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AppThumbnail.java @@ -10,7 +10,11 @@ /** The thumbnail for an app. */ @Generated public class AppThumbnail { - /** The thumbnail image bytes. */ + /** + * The thumbnail image file, such as a PNG or JPEG image. In JSON the bytes are base64-encoded. An + * update request must include a non-empty image. The service stores the image as a PNG of at most + * 320x180 pixels and crops an image that is not 16:9, so use a 16:9 image. + */ @JsonProperty("thumbnail") private String thumbnail; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AppsAPI.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AppsAPI.java index 499f42edb..0090f3eb7 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AppsAPI.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AppsAPI.java @@ -265,7 +265,7 @@ public void deleteAppThumbnail(String name) { deleteAppThumbnail(new DeleteAppThumbnailRequest().setName(name)); } - /** Deletes the thumbnail for an app. */ + /** Deletes the thumbnail for an app. Requires the CAN MANAGE permission on the app. */ public void deleteAppThumbnail(DeleteAppThumbnailRequest request) { impl.deleteAppThumbnail(request); } @@ -484,7 +484,10 @@ public AppDeploymentScanFinding updateAppDeploymentScanFinding( return impl.updateAppDeploymentScanFinding(request); } - /** Updates the thumbnail for an app. */ + /** + * Sets or replaces the thumbnail for an app. Requires the CAN MANAGE permission on the app. The + * response is an empty object and does not include the stored image. + */ public AppThumbnail updateAppThumbnail(UpdateAppThumbnailRequest request) { return impl.updateAppThumbnail(request); } diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AppsService.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AppsService.java index 03f45b9d2..8810c0987 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AppsService.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AppsService.java @@ -28,7 +28,7 @@ public interface AppsService { /** Deletes an app and the dedicated service principal created for it. */ App delete(DeleteAppRequest deleteAppRequest); - /** Deletes the thumbnail for an app. */ + /** Deletes the thumbnail for an app. Requires the CAN MANAGE permission on the app. */ void deleteAppThumbnail(DeleteAppThumbnailRequest deleteAppThumbnailRequest); /** @@ -112,7 +112,10 @@ ListAppDeploymentScanFindingsResponse listAppDeploymentScanFindings( AppDeploymentScanFinding updateAppDeploymentScanFinding( UpdateAppDeploymentScanFindingRequest updateAppDeploymentScanFindingRequest); - /** Updates the thumbnail for an app. */ + /** + * Sets or replaces the thumbnail for an app. Requires the CAN MANAGE permission on the app. The + * response is an empty object and does not include the stored image. + */ AppThumbnail updateAppThumbnail(UpdateAppThumbnailRequest updateAppThumbnailRequest); /** Updates the permissions on an app. Apps can inherit permissions from their root object. */ diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AsyncUpdateAppRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AsyncUpdateAppRequest.java index 18f3127a8..8ee3d0579 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AsyncUpdateAppRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/AsyncUpdateAppRequest.java @@ -23,7 +23,9 @@ public class AsyncUpdateAppRequest { /** * Comma-separated names of the `app` fields to update, such as `description` or `resources`. A * field named in the mask but absent from `app` is cleared, except `compute_size`, which resets - * to `MEDIUM`. Sent in the request body together with `app`. + * to `MEDIUM`. Sent in the request body together with `app`. A `*` mask does not include + * `custom_domains`; name it to set or clear them. Apps in a space can only update `description` + * and `resources`. * *

The field mask must be a single string, with multiple fields separated by commas (no * spaces). The field path is relative to the resource object, using a dot (`.`) to navigate diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/Space.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/Space.java index b52c756c0..27bd0cf9b 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/Space.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/Space.java @@ -75,6 +75,19 @@ public class Space { @JsonProperty("service_principal_name") private String servicePrincipalName; + /** + * Decides what the creator of an app in this space is granted on it. Set only at space creation. + */ + @JsonProperty("sharing_policy") + private SpaceSharingPolicy sharingPolicy; + + /** + * The kind of app space. A default space is available to every workspace user and can't be + * updated or deleted. + */ + @JsonProperty("space_type") + private SpaceType spaceType; + /** The status of the app space. */ @JsonProperty("status") private SpaceStatus status; @@ -206,6 +219,24 @@ public String getServicePrincipalName() { return servicePrincipalName; } + public Space setSharingPolicy(SpaceSharingPolicy sharingPolicy) { + this.sharingPolicy = sharingPolicy; + return this; + } + + public SpaceSharingPolicy getSharingPolicy() { + return sharingPolicy; + } + + public Space setSpaceType(SpaceType spaceType) { + this.spaceType = spaceType; + return this; + } + + public SpaceType getSpaceType() { + return spaceType; + } + public Space setStatus(SpaceStatus status) { this.status = status; return this; @@ -268,6 +299,8 @@ public boolean equals(Object o) { && Objects.equals(servicePrincipalClientId, that.servicePrincipalClientId) && Objects.equals(servicePrincipalId, that.servicePrincipalId) && Objects.equals(servicePrincipalName, that.servicePrincipalName) + && Objects.equals(sharingPolicy, that.sharingPolicy) + && Objects.equals(spaceType, that.spaceType) && Objects.equals(status, that.status) && Objects.equals(updateTime, that.updateTime) && Objects.equals(updater, that.updater) @@ -290,6 +323,8 @@ public int hashCode() { servicePrincipalClientId, servicePrincipalId, servicePrincipalName, + sharingPolicy, + spaceType, status, updateTime, updater, @@ -312,6 +347,8 @@ public String toString() { .add("servicePrincipalClientId", servicePrincipalClientId) .add("servicePrincipalId", servicePrincipalId) .add("servicePrincipalName", servicePrincipalName) + .add("sharingPolicy", sharingPolicy) + .add("spaceType", spaceType) .add("status", status) .add("updateTime", updateTime) .add("updater", updater) diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/SpaceSharingPolicy.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/SpaceSharingPolicy.java new file mode 100644 index 000000000..f17844805 --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/SpaceSharingPolicy.java @@ -0,0 +1,10 @@ +// Code generated from OpenAPI specs by Databricks SDK Generator. DO NOT EDIT. + +package com.databricks.sdk.service.apps; + +import com.databricks.sdk.support.Generated; + +@Generated +public enum SpaceSharingPolicy { + CREATOR_CANNOT_SHARE, +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/SpaceType.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/SpaceType.java new file mode 100644 index 000000000..dcc8d1eb1 --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/apps/SpaceType.java @@ -0,0 +1,12 @@ +// Code generated from OpenAPI specs by Databricks SDK Generator. DO NOT EDIT. + +package com.databricks.sdk.service.apps; + +import com.databricks.sdk.support.Generated; + +/** The kind of app space. */ +@Generated +public enum SpaceType { + SPACE_TYPE_DEFAULT, + SPACE_TYPE_STANDARD, +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BatchUpdateOperationsRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BatchUpdateOperationsRequest.java new file mode 100644 index 000000000..4468b7371 --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BatchUpdateOperationsRequest.java @@ -0,0 +1,63 @@ +// Code generated from OpenAPI specs by Databricks SDK Generator. DO NOT EDIT. + +package com.databricks.sdk.service.bundledeployments; + +import com.databricks.sdk.support.Generated; +import com.databricks.sdk.support.ToStringer; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Collection; +import java.util.Objects; + +/** A request to update operations in a single version atomically. */ +@Generated +public class BatchUpdateOperationsRequest { + /** The parent version. Format: deployments/{deployment_id}/versions/{version_id} */ + @JsonIgnore private String parent; + + /** + * Provide between 1 and 20 updates. Operations must be distinct and belong to parent. Clients + * should keep the total serialized request size below 1 MiB. + */ + @JsonProperty("requests") + private Collection requests; + + public BatchUpdateOperationsRequest setParent(String parent) { + this.parent = parent; + return this; + } + + public String getParent() { + return parent; + } + + public BatchUpdateOperationsRequest setRequests(Collection requests) { + this.requests = requests; + return this; + } + + public Collection getRequests() { + return requests; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + BatchUpdateOperationsRequest that = (BatchUpdateOperationsRequest) o; + return Objects.equals(parent, that.parent) && Objects.equals(requests, that.requests); + } + + @Override + public int hashCode() { + return Objects.hash(parent, requests); + } + + @Override + public String toString() { + return new ToStringer(BatchUpdateOperationsRequest.class) + .add("parent", parent) + .add("requests", requests) + .toString(); + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BatchUpdateOperationsResponse.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BatchUpdateOperationsResponse.java new file mode 100644 index 000000000..7d98923e2 --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BatchUpdateOperationsResponse.java @@ -0,0 +1,49 @@ +// Code generated from OpenAPI specs by Databricks SDK Generator. DO NOT EDIT. + +package com.databricks.sdk.service.bundledeployments; + +import com.databricks.sdk.support.Generated; +import com.databricks.sdk.support.ToStringer; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Collection; +import java.util.Objects; + +/** The response contains updated operations in request order after every update succeeds. */ +@Generated +public class BatchUpdateOperationsResponse { + /** + * The updated operations in the same order as the requests. Like UpdateOperation, returned + * operations omit state; read it from Resources. + */ + @JsonProperty("operations") + private Collection operations; + + public BatchUpdateOperationsResponse setOperations(Collection operations) { + this.operations = operations; + return this; + } + + public Collection getOperations() { + return operations; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + BatchUpdateOperationsResponse that = (BatchUpdateOperationsResponse) o; + return Objects.equals(operations, that.operations); + } + + @Override + public int hashCode() { + return Objects.hash(operations); + } + + @Override + public String toString() { + return new ToStringer(BatchUpdateOperationsResponse.class) + .add("operations", operations) + .toString(); + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BundleDeploymentsAPI.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BundleDeploymentsAPI.java index 87bb980f5..b2169fe38 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BundleDeploymentsAPI.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BundleDeploymentsAPI.java @@ -6,6 +6,7 @@ import com.databricks.sdk.core.logging.LoggerFactory; import com.databricks.sdk.support.Generated; import com.databricks.sdk.support.Paginator; +import java.util.Collection; /** Service for managing bundle deployment metadata. */ @Generated @@ -24,6 +25,30 @@ public BundleDeploymentsAPI(BundleDeploymentsService mock) { impl = mock; } + /** + * Updates between 1 and 20 operations belonging to the same in-progress version atomically. + * + *

Each request follows the update mask and sequence_id rules of UpdateOperation. Every + * operation must be distinct and belong to parent. If any update fails, none of the operations or + * their resources are changed. Updated operations are returned in the same order as the requests. + * Clients should keep the total serialized request below 1 MiB. + */ + public BatchUpdateOperationsResponse batchUpdateOperations(BatchUpdateOperationsRequest request) { + return impl.batchUpdateOperations(request); + } + + public CheckEnrollmentsResponse checkEnrollments(Collection features) { + return checkEnrollments(new CheckEnrollmentsRequest().setFeatures(features)); + } + + /** + * Reports which of the requested features the calling workspace is enrolled in. If the call fails + * or the method is not available, treat the workspace as not enrolled in any feature. + */ + public CheckEnrollmentsResponse checkEnrollments(CheckEnrollmentsRequest request) { + return impl.checkEnrollments(request); + } + /** * Marks a version as complete and releases the deployment lock. * diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BundleDeploymentsImpl.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BundleDeploymentsImpl.java index 943f37624..7cdb9d200 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BundleDeploymentsImpl.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BundleDeploymentsImpl.java @@ -16,6 +16,41 @@ public BundleDeploymentsImpl(ApiClient apiClient) { this.apiClient = apiClient; } + @Override + public BatchUpdateOperationsResponse batchUpdateOperations(BatchUpdateOperationsRequest request) { + String path = String.format("/api/2.0/bundle/%s/operations:batchUpdate", request.getParent()); + try { + Request req = new Request("POST", path, apiClient.serialize(request)); + + ApiClient.setQuery(req, request); + req.withHeader("Accept", "application/json"); + req.withHeader("Content-Type", "application/json"); + if (apiClient.workspaceId() != null) { + req.withHeader("X-Databricks-Workspace-Id", apiClient.workspaceId()); + } + return apiClient.execute(req, BatchUpdateOperationsResponse.class); + } catch (IOException e) { + throw new DatabricksException("IO error: " + e.getMessage(), e); + } + } + + @Override + public CheckEnrollmentsResponse checkEnrollments(CheckEnrollmentsRequest request) { + String path = "/api/2.0/bundle/enrollments:check"; + try { + Request req = new Request("GET", path); + + ApiClient.setQuery(req, request); + req.withHeader("Accept", "application/json"); + if (apiClient.workspaceId() != null) { + req.withHeader("X-Databricks-Workspace-Id", apiClient.workspaceId()); + } + return apiClient.execute(req, CheckEnrollmentsResponse.class); + } catch (IOException e) { + throw new DatabricksException("IO error: " + e.getMessage(), e); + } + } + @Override public Version completeVersion(CompleteVersionRequest request) { String path = String.format("/api/2.0/bundle/%s/complete", request.getName()); diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BundleDeploymentsService.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BundleDeploymentsService.java index a0a580958..0064db020 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BundleDeploymentsService.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/BundleDeploymentsService.java @@ -12,6 +12,23 @@ */ @Generated public interface BundleDeploymentsService { + /** + * Updates between 1 and 20 operations belonging to the same in-progress version atomically. + * + *

Each request follows the update mask and sequence_id rules of UpdateOperation. Every + * operation must be distinct and belong to parent. If any update fails, none of the operations or + * their resources are changed. Updated operations are returned in the same order as the requests. + * Clients should keep the total serialized request below 1 MiB. + */ + BatchUpdateOperationsResponse batchUpdateOperations( + BatchUpdateOperationsRequest batchUpdateOperationsRequest); + + /** + * Reports which of the requested features the calling workspace is enrolled in. If the call fails + * or the method is not available, treat the workspace as not enrolled in any feature. + */ + CheckEnrollmentsResponse checkEnrollments(CheckEnrollmentsRequest checkEnrollmentsRequest); + /** * Marks a version as complete and releases the deployment lock. * diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/CheckEnrollmentsRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/CheckEnrollmentsRequest.java new file mode 100644 index 000000000..b9650a210 --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/CheckEnrollmentsRequest.java @@ -0,0 +1,48 @@ +// Code generated from OpenAPI specs by Databricks SDK Generator. DO NOT EDIT. + +package com.databricks.sdk.service.bundledeployments; + +import com.databricks.sdk.support.Generated; +import com.databricks.sdk.support.QueryParam; +import com.databricks.sdk.support.ToStringer; +import com.fasterxml.jackson.annotation.JsonIgnore; +import java.util.Collection; +import java.util.Objects; + +@Generated +public class CheckEnrollmentsRequest { + /** + * Names of the features to check, for example `record_history_auto`. Provide at least 1 and at + * most 100 names. Duplicates are ignored. + */ + @JsonIgnore + @QueryParam("features") + private Collection features; + + public CheckEnrollmentsRequest setFeatures(Collection features) { + this.features = features; + return this; + } + + public Collection getFeatures() { + return features; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + CheckEnrollmentsRequest that = (CheckEnrollmentsRequest) o; + return Objects.equals(features, that.features); + } + + @Override + public int hashCode() { + return Objects.hash(features); + } + + @Override + public String toString() { + return new ToStringer(CheckEnrollmentsRequest.class).add("features", features).toString(); + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/CheckEnrollmentsResponse.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/CheckEnrollmentsResponse.java new file mode 100644 index 000000000..11e932315 --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/CheckEnrollmentsResponse.java @@ -0,0 +1,53 @@ +// Code generated from OpenAPI specs by Databricks SDK Generator. DO NOT EDIT. + +package com.databricks.sdk.service.bundledeployments; + +import com.databricks.sdk.support.Generated; +import com.databricks.sdk.support.ToStringer; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; +import java.util.Objects; + +/** + * Reports, for each requested feature that the service recognizes, whether the calling workspace is + * enrolled in it. + */ +@Generated +public class CheckEnrollmentsResponse { + /** + * Whether the workspace is enrolled in each requested feature that the service recognizes, keyed + * by feature name. A feature the service does not recognize is omitted; clients must treat a + * missing key as not enrolled. + */ + @JsonProperty("enrollments") + private Map enrollments; + + public CheckEnrollmentsResponse setEnrollments(Map enrollments) { + this.enrollments = enrollments; + return this; + } + + public Map getEnrollments() { + return enrollments; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + CheckEnrollmentsResponse that = (CheckEnrollmentsResponse) o; + return Objects.equals(enrollments, that.enrollments); + } + + @Override + public int hashCode() { + return Objects.hash(enrollments); + } + + @Override + public String toString() { + return new ToStringer(CheckEnrollmentsResponse.class) + .add("enrollments", enrollments) + .toString(); + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/Operation.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/Operation.java index d495ab995..0172eaf07 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/Operation.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/Operation.java @@ -83,11 +83,11 @@ public class Operation { * Monotonically increasing revision used for optimistic concurrency control (the AIP-154 * concurrency token for this resource, realized as a sequence number rather than an opaque etag). * The server assigns 0 when the operation is created and increments it on every successful - * UpdateOperation, so a never-updated operation is at 0 and the first successful update makes it - * 1. It is OPTIONAL rather than OUTPUT_ONLY because it is dual-purpose: GetOperation returns the - * current value, and UpdateOperation reads the caller-supplied value as a precondition. The - * caller must echo the value it last observed; if it no longer matches the server's value, the - * update is rejected with ABORTED so the caller can re-read and retry. + * UpdateOperation or BatchUpdateOperations. The first successful update changes it from 0 to 1. + * It is OPTIONAL rather than OUTPUT_ONLY because it is dual-purpose: reads return the current + * value, and updates require the caller-supplied value as a precondition, including 0 for the + * first update. The caller must echo the value it last observed; if it no longer matches the + * server's value, the update is rejected with ABORTED so the caller can re-read and retry. */ @JsonProperty("sequence_id") private Long sequenceId; @@ -126,7 +126,7 @@ public class Operation { /** * When the operation was last updated. Set to `create_time` when the operation is created and to - * the server timestamp on each successful UpdateOperation. + * the server timestamp on each successful UpdateOperation or BatchUpdateOperations. */ @JsonProperty("update_time") private Timestamp updateTime; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/UpdateOperationRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/UpdateOperationRequest.java index f0b6e2509..fceda7267 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/UpdateOperationRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/bundledeployments/UpdateOperationRequest.java @@ -10,6 +10,10 @@ import com.google.protobuf.FieldMask; import java.util.Objects; +/** + * A request to update an Operation. Only `state`, `error_message`, `resource_id`, `status`, and + * `dashboard_metadata` may be updated. + */ @Generated public class UpdateOperationRequest { /** @@ -30,8 +34,18 @@ public class UpdateOperationRequest { * The set of fields to update. Required; supported paths are `state`, `error_message`, * `resource_id`, `status`, and `dashboard_metadata`. An empty mask or any other path is rejected * with INVALID_PARAMETER_VALUE. + * + *

The field mask must be a single string, with multiple fields separated by commas (no + * spaces). The field path is relative to the resource object, using a dot (`.`) to navigate + * sub-fields (e.g., `author.given_name`). Specification of elements in sequence or map fields is + * not allowed, as only the entire collection field can be specified. Field names must exactly + * match the resource field names. + * + *

A field mask of `*` indicates full replacement. It’s recommended to always explicitly list + * the fields being updated and avoid using `*` wildcards, as it can lead to unintended results if + * the API changes in the future. */ - @JsonIgnore + @JsonProperty("update_mask") @QueryParam("update_mask") private FieldMask updateMask; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/AiGatewayAPI.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/AiGatewayAPI.java index bafbe5ece..0f95645c1 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/AiGatewayAPI.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/AiGatewayAPI.java @@ -422,10 +422,10 @@ public ModelService updateModelService(UpdateModelServiceRequest request) { } /** - * Updates a skill. Only fields named in `update_mask` are changed; currently only `comment` is + * Updates a skill. Only fields named in `update_mask` are changed; currently `comment` is * supported. The resource name is immutable. Optionally supply an `etag` to make the update - * conditional on the skill not having changed since it was read. Bundle files, grants, tags, and - * ownership are unchanged. + * conditional on the skill not having changed since it was read. Bundle files, grants, and tags + * are unchanged. * *

To update the bundle, add, overwrite (`overwrite=true`), or delete files under * `/Skills/{catalog}/{schema}/{skill}/` with the Files API, then call FinalizeSkill. Changing diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/AiGatewayService.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/AiGatewayService.java index f7c1c5d86..5e0fd6cfd 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/AiGatewayService.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/AiGatewayService.java @@ -277,10 +277,10 @@ ModelProviderService updateModelProviderService( ModelService updateModelService(UpdateModelServiceRequest updateModelServiceRequest); /** - * Updates a skill. Only fields named in `update_mask` are changed; currently only `comment` is + * Updates a skill. Only fields named in `update_mask` are changed; currently `comment` is * supported. The resource name is immutable. Optionally supply an `etag` to make the update - * conditional on the skill not having changed since it was read. Bundle files, grants, tags, and - * ownership are unchanged. + * conditional on the skill not having changed since it was read. Bundle files, grants, and tags + * are unchanged. * *

To update the bundle, add, overwrite (`overwrite=true`), or delete files under * `/Skills/{catalog}/{schema}/{skill}/` with the Files API, then call FinalizeSkill. Changing diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/CreateSkillRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/CreateSkillRequest.java index e33849ab2..d5897b8c3 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/CreateSkillRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/CreateSkillRequest.java @@ -20,8 +20,9 @@ public class CreateSkillRequest { private String parent; /** - * The skill to create. `comment` is the only accepted client input and may be omitted. Do not set - * `name`; the server derives it from `parent` and `skill_id`. + * The skill to create. `comment` is the only accepted client input and may be omitted. + * CreateSkill rejects `owner`; use UpdateSkill with `owner` in the `update_mask` to transfer + * ownership. Do not set `name`; the server derives it from `parent` and `skill_id`. */ @JsonProperty("skill") private Skill skill; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/InferenceTableConfig.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/InferenceTableConfig.java index 0244d5dd4..187b07d3c 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/InferenceTableConfig.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/InferenceTableConfig.java @@ -13,6 +13,14 @@ */ @Generated public class InferenceTableConfig { + /** + * Whether payload logging is disabled. Logging is enabled by default. Set this to `true` to pause + * logging without deleting the inference table or its configuration. `parent` remains required + * when logging is disabled. + */ + @JsonProperty("disabled") + private Boolean disabled; + /** * Whether the referenced inference table has been deleted. The configuration remains visible so * you can identify the broken dependency. Payload logging cannot continue until the table is @@ -45,6 +53,15 @@ public class InferenceTableConfig { @JsonProperty("table_name_prefix") private String tableNamePrefix; + public InferenceTableConfig setDisabled(Boolean disabled) { + this.disabled = disabled; + return this; + } + + public Boolean getDisabled() { + return disabled; + } + public InferenceTableConfig setIsDeleted(Boolean isDeleted) { this.isDeleted = isDeleted; return this; @@ -86,7 +103,8 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InferenceTableConfig that = (InferenceTableConfig) o; - return Objects.equals(isDeleted, that.isDeleted) + return Objects.equals(disabled, that.disabled) + && Objects.equals(isDeleted, that.isDeleted) && Objects.equals(parent, that.parent) && Objects.equals(table, that.table) && Objects.equals(tableNamePrefix, that.tableNamePrefix); @@ -94,12 +112,13 @@ public boolean equals(Object o) { @Override public int hashCode() { - return Objects.hash(isDeleted, parent, table, tableNamePrefix); + return Objects.hash(disabled, isDeleted, parent, table, tableNamePrefix); } @Override public String toString() { return new ToStringer(InferenceTableConfig.class) + .add("disabled", disabled) .add("isDeleted", isDeleted) .add("parent", parent) .add("table", table) diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/ListSkillsRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/ListSkillsRequest.java index 4bb2ddaa1..2d74de8e5 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/ListSkillsRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/ListSkillsRequest.java @@ -25,10 +25,8 @@ public class ListSkillsRequest { /** * Name of the parent schema. Format: `schemas/{catalog}.{schema}`. Each `{...}` component is - * capped at 255 characters individually. - * - *

Required: skill listing is schema-scoped, so `parent` must be set; an unset or empty - * `parent` is rejected with INVALID_PARAMETER_VALUE. + * capped at 255 characters individually. Required: skill listing is schema-scoped, so `parent` + * must be set; an unset or empty `parent` is rejected with INVALID_PARAMETER_VALUE. */ @JsonIgnore @QueryParam("parent") diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/UpdateModelProviderServiceRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/UpdateModelProviderServiceRequest.java index 4071d775d..c75d843b0 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/UpdateModelProviderServiceRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/UpdateModelProviderServiceRequest.java @@ -38,12 +38,13 @@ public class UpdateModelProviderServiceRequest { @JsonIgnore private String name; /** - * Fields to update. Use `config` to replace the entire configuration. The replacement must - * include every required field; any optional field you omit is cleared. To preserve sibling - * fields, use one or more granular paths: `comment`; `config.provider` to replace the active - * provider-specific value (for example, `config.openai`; the mask path remains - * `config.provider`); `config.allow_all_targets`, `config.targets`, `config.forward_headers`, - * `config.forward_query_parameters`, `config.forward_unmanaged_paths`, `config.rate_limits`, + * Fields to update. Use `config` to replace the configuration's supported fields. The replacement + * must include every required field. Omitted optional fields in the published schema are cleared, + * except for the authentication binding described below. To preserve sibling fields, use granular + * paths: `comment`; `config.provider` to replace the active provider-specific value (for example, + * `config.openai`; the mask path remains `config.provider`); `config.allow_all_targets`, + * `config.targets`, `config.forward_headers`, `config.forward_query_parameters`, + * `config.forward_unmanaged_paths`, `config.rate_limits`, * `config.pricing.default_discount_basis_points`, or `config.inference_table`. For a pricing * update, an explicitly empty `pricing` object clears the discount but retains the object; * omitting `pricing` clears it. `config.pricing` is not a supported mask path. The provider type diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/UpdateModelServiceRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/UpdateModelServiceRequest.java index 2b773a089..0abb09e80 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/UpdateModelServiceRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/UpdateModelServiceRequest.java @@ -38,9 +38,9 @@ public class UpdateModelServiceRequest { @JsonIgnore private String name; /** - * Fields to update. Use `config` for a broad configuration replacement. The replacement must - * include every required field; optional fields in its replacement scope are cleared when - * omitted. To preserve sibling fields, use one or more granular paths: `comment`, + * Fields to update. Use `config` to replace the configuration's supported fields. The replacement + * must include every required field. Omitted optional fields in the published schema are cleared. + * To preserve sibling fields, use one or more granular paths: `comment`, * `config.routing.destinations`, `config.routing.fallback.destinations`, `config.rate_limits`, or * `config.inference_table`. Intermediate paths such as `config.routing` and * `config.routing.fallback` are not supported. diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/UpdateSecretRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/UpdateSecretRequest.java index 0723c6588..1a8e25d66 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/UpdateSecretRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/catalog/UpdateSecretRequest.java @@ -27,10 +27,10 @@ public class UpdateSecretRequest { /** * The field mask specifying which fields of the secret to update. - If **update_mask** is - * **"*"**, all fields specified in **secret** are updated. - If **update_mask** specifies one or - * more fields, only those fields are updated. Each specified field must be set in **secret**. - * Supported fields: **value**, **comment**, **owner**, **expire_time**. To change the secret - * name, delete and recreate the secret. + * **"*"**, all fields specified in **secret** are updated. - To update individual fields, list + * them in **update_mask** and supply their values in **secret**. Supported fields: **value**, + * **comment**, **owner**, **expire_time**. To change the secret name, delete and recreate the + * secret. */ @JsonIgnore @QueryParam("update_mask") diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/domains/CreateDomainRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/domains/CreateDomainRequest.java index da5c4efe4..1cfd32762 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/domains/CreateDomainRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/domains/CreateDomainRequest.java @@ -11,7 +11,9 @@ @Generated public class CreateDomainRequest { - /** */ + /** + * The domain to create. `tag_key` must be set; it binds the domain to an existing tag policy key. + */ @JsonProperty("domain") private Domain domain; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/domains/ListDomainsRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/domains/ListDomainsRequest.java index 39f8ba01a..db3d53725 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/domains/ListDomainsRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/domains/ListDomainsRequest.java @@ -10,12 +10,15 @@ @Generated public class ListDomainsRequest { - /** */ + /** + * Maximum number of domains to return in a single page. Must be positive and at most 1000; + * defaults to 1000 when omitted. + */ @JsonIgnore @QueryParam("page_size") private Long pageSize; - /** */ + /** Pagination token from a previous ListDomainsResponse. Returns the first page when absent. */ @JsonIgnore @QueryParam("page_token") private String pageToken; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/domains/ListDomainsResponse.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/domains/ListDomainsResponse.java index 0da157431..62ccae3cb 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/domains/ListDomainsResponse.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/domains/ListDomainsResponse.java @@ -10,11 +10,11 @@ @Generated public class ListDomainsResponse { - /** */ + /** The domains on the requested page. */ @JsonProperty("domains") private Collection domains; - /** */ + /** Pagination token to request the next page of domains. Absent when no further pages remain. */ @JsonProperty("next_page_token") private String nextPageToken; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/domains/UpdateDomainRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/domains/UpdateDomainRequest.java index c3d8626fe..bd189379c 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/domains/UpdateDomainRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/domains/UpdateDomainRequest.java @@ -12,7 +12,10 @@ @Generated public class UpdateDomainRequest { - /** */ + /** + * The domain to update. Its `name` field (`domains/{domain_id}`) identifies the domain; masked + * fields are replaced with the values supplied here. + */ @JsonProperty("domain") private Domain domain; @@ -24,15 +27,8 @@ public class UpdateDomainRequest { @JsonIgnore private String name; /** - * The field mask must be a single string, with multiple fields separated by commas (no spaces). - * The field path is relative to the resource object, using a dot (`.`) to navigate sub-fields - * (e.g., `author.given_name`). Specification of elements in sequence or map fields is not - * allowed, as only the entire collection field can be specified. Field names must exactly match - * the resource field names. - * - *

A field mask of `*` indicates full replacement. It’s recommended to always explicitly list - * the fields being updated and avoid using `*` wildcards, as it can lead to unintended results if - * the API changes in the future. + * The field mask specifying which fields of the domain to update. Must be non-empty. Fields not + * in the mask keep their existing values. */ @JsonIgnore @QueryParam("update_mask") diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/files/FilesAPI.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/files/FilesAPI.java index f05437b57..463568e1d 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/files/FilesAPI.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/files/FilesAPI.java @@ -45,6 +45,7 @@ public FilesAPI(FilesService mock) { * Creates an empty directory. If necessary, also creates any parent directories of the new, empty * directory (like the shell command `mkdir -p`). If called on an existing directory, returns a * success response; this method is idempotent (it will succeed if the directory already exists). + * If the path itself is an existing file, returns 409 RESOURCE_CONFLICT. */ public void createDirectory(CreateDirectoryRequest request) { impl.createDirectory(request); diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/files/FilesService.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/files/FilesService.java index 91b942fd1..7965c4490 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/files/FilesService.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/files/FilesService.java @@ -31,6 +31,7 @@ public interface FilesService { * Creates an empty directory. If necessary, also creates any parent directories of the new, empty * directory (like the shell command `mkdir -p`). If called on an existing directory, returns a * success response; this method is idempotent (it will succeed if the directory already exists). + * If the path itself is an existing file, returns 409 RESOURCE_CONFLICT. */ void createDirectory(CreateDirectoryRequest createDirectoryRequest); diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/geniemigrate/DestinationKind.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/geniemigrate/DestinationKind.java index 69702e023..b403ba729 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/geniemigrate/DestinationKind.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/geniemigrate/DestinationKind.java @@ -7,7 +7,6 @@ /** Destination asset kind for a converted file. */ @Generated public enum DestinationKind { - DESTINATION_KIND_DESIGNER_FILE, DESTINATION_KIND_FILE, DESTINATION_KIND_NOTEBOOK, DESTINATION_KIND_QUERY, diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/geniemigrate/Project.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/geniemigrate/Project.java index 30f00ddb5..fe01f5706 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/geniemigrate/Project.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/geniemigrate/Project.java @@ -25,10 +25,7 @@ public class Project { @JsonProperty("create_time") private Timestamp createTime; - /** - * The display name of the project. Required on create, and can't be blank. Changing it renames - * the project. - */ + /** The display name of the project. Required on create, and can't be blank. */ @JsonProperty("display_name") private String displayName; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/geniemigrate/SourceDialect.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/geniemigrate/SourceDialect.java index 857f313d9..3f0f2ae87 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/geniemigrate/SourceDialect.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/geniemigrate/SourceDialect.java @@ -7,13 +7,10 @@ /** Source dialect of the files in a migration project. */ @Generated public enum SourceDialect { - SOURCE_DIALECT_ALTERYX, SOURCE_DIALECT_BIGQUERY, - SOURCE_DIALECT_INFORMATICA, SOURCE_DIALECT_ORACLE, SOURCE_DIALECT_REDSHIFT, SOURCE_DIALECT_SNOWFLAKE, - SOURCE_DIALECT_SSIS, SOURCE_DIALECT_TERADATA, SOURCE_DIALECT_T_SQL, } diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/geniemigrate/TargetFramework.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/geniemigrate/TargetFramework.java index cd02fdb8d..beb4bb4a3 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/geniemigrate/TargetFramework.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/geniemigrate/TargetFramework.java @@ -7,8 +7,6 @@ /** Output framework of the converted files in a migration project. */ @Generated public enum TargetFramework { - TARGET_FRAMEWORK_DESIGNER, TARGET_FRAMEWORK_PYSPARK, - TARGET_FRAMEWORK_SPARK_DECLARATIVE_PIPELINES, TARGET_FRAMEWORK_SQL, } diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/iam/CreateRestrictedSharingGroupRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/iam/CreateRestrictedSharingGroupRequest.java index 3b05831b6..bed4e1dad 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/iam/CreateRestrictedSharingGroupRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/iam/CreateRestrictedSharingGroupRequest.java @@ -19,8 +19,8 @@ public class CreateRestrictedSharingGroupRequest { private RestrictedSharingGroup restrictedSharingGroup; /** - * The id of the workspace group to restrict: the numeric id of an existing and non-system - * workspace group. + * The numeric id of the group to restrict. The group must belong to the caller's account and + * can't be a system group. */ @JsonIgnore @QueryParam("restricted_sharing_group_id") diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/iam/ListRestrictedSharingGroupsResponse.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/iam/ListRestrictedSharingGroupsResponse.java index 594757bb3..c4d29057a 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/iam/ListRestrictedSharingGroupsResponse.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/iam/ListRestrictedSharingGroupsResponse.java @@ -18,7 +18,10 @@ public class ListRestrictedSharingGroupsResponse { @JsonProperty("next_page_token") private String nextPageToken; - /** The restricted sharing groups in the workspace. */ + /** + * The restricted sharing groups in the workspace. Only groups that still belong to the caller's + * account are returned. + */ @JsonProperty("restricted_sharing_groups") private Collection restrictedSharingGroups; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/iam/PermissionLevel.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/iam/PermissionLevel.java index bfd2f524b..05b184bff 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/iam/PermissionLevel.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/iam/PermissionLevel.java @@ -9,6 +9,7 @@ public enum PermissionLevel { CAN_ATTACH_TO, CAN_BIND, + CAN_BUILD, CAN_CREATE, CAN_CREATE_APP, CAN_EDIT, diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/iam/RestrictedSharingGroup.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/iam/RestrictedSharingGroup.java index 19911ff60..05d54260f 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/iam/RestrictedSharingGroup.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/iam/RestrictedSharingGroup.java @@ -8,13 +8,14 @@ import java.util.Objects; /** - * A RestrictedSharingGroup is a workspace group whose members cannot grant or revoke permissions on - * workspace assets while they have assumed the group or one of its child groups. Users acting as - * themselves are not affected. + * A RestrictedSharingGroup is a group on the workspace's restrict sharing list. The group must + * belong to the caller's account. A user or service principal acting as the group, or as a group + * nested under it, can't share workspace assets owned by that group. Users and service principals + * acting as their own identities aren't affected. */ @Generated public class RestrictedSharingGroup { - /** The display name of the restricted workspace group. */ + /** The display name of the restricted group. */ @JsonProperty("group_display_name") private String groupDisplayName; @@ -27,8 +28,8 @@ public class RestrictedSharingGroup { private String name; /** - * The id of the restricted workspace group: the numeric id of an existing and non-system - * workspace group. + * The numeric id of the restricted group. The group must belong to the caller's account and can't + * be a system group. */ @JsonProperty("restricted_sharing_group_id") private String restrictedSharingGroupId; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/lakewatch/ResourceStatus.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/lakewatch/ResourceStatus.java index 18ef55574..8a4577d19 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/lakewatch/ResourceStatus.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/lakewatch/ResourceStatus.java @@ -38,7 +38,10 @@ public class ResourceStatus { @JsonProperty("last_complete_time") private Timestamp lastCompleteTime; - /** Most recent error message, if any. Pairs with `run_state = FAILED`. */ + /** + * Most recent error message or inactive event recovery capture diagnostic, if any. A capture + * diagnostic does not change the job or pipeline's `run_state`. + */ @JsonProperty("last_error_message") private String lastErrorMessage; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/ExperimentsAPI.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/ExperimentsAPI.java index 37cfa9030..bad1e5150 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/ExperimentsAPI.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/ExperimentsAPI.java @@ -311,7 +311,7 @@ public void logInputs(LogInputs request) { * Logs params for a logged model. A param is a key-value pair (string key, string value). * Examples include hyperparameters used for ML model training. A param can be logged only once * for a logged model, and attempting to overwrite an existing param with a different value will - * result in an error + * result in an error. */ public void logLoggedModelParams(LogLoggedModelParamsRequest request) { impl.logLoggedModelParams(request); diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/ExperimentsService.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/ExperimentsService.java index 5c89c2746..94849f46a 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/ExperimentsService.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/ExperimentsService.java @@ -182,7 +182,7 @@ ExperimentPermissions getPermissions( * Logs params for a logged model. A param is a key-value pair (string key, string value). * Examples include hyperparameters used for ML model training. A param can be logged only once * for a logged model, and attempting to overwrite an existing param with a different value will - * result in an error + * result in an error. */ void logLoggedModelParams(LogLoggedModelParamsRequest logLoggedModelParamsRequest); diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/FirstDistinctFunction.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/FirstDistinctFunction.java index 552310260..8886f42f9 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/FirstDistinctFunction.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/FirstDistinctFunction.java @@ -10,6 +10,10 @@ /** Returns the first N distinct values, ordered by the feature's timeseries column. */ @Generated public class FirstDistinctFunction { + /** When true, rows whose input is NULL are skipped. */ + @JsonProperty("ignore_nulls") + private Boolean ignoreNulls; + /** The input column from which the first N distinct values are returned. */ @JsonProperty("input") private String input; @@ -18,6 +22,15 @@ public class FirstDistinctFunction { @JsonProperty("n") private Long n; + public FirstDistinctFunction setIgnoreNulls(Boolean ignoreNulls) { + this.ignoreNulls = ignoreNulls; + return this; + } + + public Boolean getIgnoreNulls() { + return ignoreNulls; + } + public FirstDistinctFunction setInput(String input) { this.input = input; return this; @@ -41,16 +54,22 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FirstDistinctFunction that = (FirstDistinctFunction) o; - return Objects.equals(input, that.input) && Objects.equals(n, that.n); + return Objects.equals(ignoreNulls, that.ignoreNulls) + && Objects.equals(input, that.input) + && Objects.equals(n, that.n); } @Override public int hashCode() { - return Objects.hash(input, n); + return Objects.hash(ignoreNulls, input, n); } @Override public String toString() { - return new ToStringer(FirstDistinctFunction.class).add("input", input).add("n", n).toString(); + return new ToStringer(FirstDistinctFunction.class) + .add("ignoreNulls", ignoreNulls) + .add("input", input) + .add("n", n) + .toString(); } } diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/FirstFunction.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/FirstFunction.java index 89d43e6a7..95c6a8b95 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/FirstFunction.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/FirstFunction.java @@ -10,10 +10,23 @@ /** Returns the first value. */ @Generated public class FirstFunction { + /** When true, rows whose input is NULL are skipped. */ + @JsonProperty("ignore_nulls") + private Boolean ignoreNulls; + /** The input column from which the first value is returned. */ @JsonProperty("input") private String input; + public FirstFunction setIgnoreNulls(Boolean ignoreNulls) { + this.ignoreNulls = ignoreNulls; + return this; + } + + public Boolean getIgnoreNulls() { + return ignoreNulls; + } + public FirstFunction setInput(String input) { this.input = input; return this; @@ -28,16 +41,19 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FirstFunction that = (FirstFunction) o; - return Objects.equals(input, that.input); + return Objects.equals(ignoreNulls, that.ignoreNulls) && Objects.equals(input, that.input); } @Override public int hashCode() { - return Objects.hash(input); + return Objects.hash(ignoreNulls, input); } @Override public String toString() { - return new ToStringer(FirstFunction.class).add("input", input).toString(); + return new ToStringer(FirstFunction.class) + .add("ignoreNulls", ignoreNulls) + .add("input", input) + .toString(); } } diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/FirstNFunction.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/FirstNFunction.java index 771764cac..4b45da316 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/FirstNFunction.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/FirstNFunction.java @@ -10,6 +10,10 @@ /** Returns the first N values, ordered by the feature's timeseries column. */ @Generated public class FirstNFunction { + /** When true, rows whose input is NULL are skipped. */ + @JsonProperty("ignore_nulls") + private Boolean ignoreNulls; + /** The input column from which the first N values are returned. */ @JsonProperty("input") private String input; @@ -18,6 +22,15 @@ public class FirstNFunction { @JsonProperty("n") private Long n; + public FirstNFunction setIgnoreNulls(Boolean ignoreNulls) { + this.ignoreNulls = ignoreNulls; + return this; + } + + public Boolean getIgnoreNulls() { + return ignoreNulls; + } + public FirstNFunction setInput(String input) { this.input = input; return this; @@ -41,16 +54,22 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FirstNFunction that = (FirstNFunction) o; - return Objects.equals(input, that.input) && Objects.equals(n, that.n); + return Objects.equals(ignoreNulls, that.ignoreNulls) + && Objects.equals(input, that.input) + && Objects.equals(n, that.n); } @Override public int hashCode() { - return Objects.hash(input, n); + return Objects.hash(ignoreNulls, input, n); } @Override public String toString() { - return new ToStringer(FirstNFunction.class).add("input", input).add("n", n).toString(); + return new ToStringer(FirstNFunction.class) + .add("ignoreNulls", ignoreNulls) + .add("input", input) + .add("n", n) + .toString(); } } diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LastDistinctFunction.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LastDistinctFunction.java index 76c6de35e..9de5072e3 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LastDistinctFunction.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LastDistinctFunction.java @@ -10,6 +10,10 @@ /** Returns the last N distinct values, ordered by the feature's timeseries column. */ @Generated public class LastDistinctFunction { + /** When true, rows whose input is NULL are skipped. */ + @JsonProperty("ignore_nulls") + private Boolean ignoreNulls; + /** The input column from which the last N distinct values are returned. */ @JsonProperty("input") private String input; @@ -18,6 +22,15 @@ public class LastDistinctFunction { @JsonProperty("n") private Long n; + public LastDistinctFunction setIgnoreNulls(Boolean ignoreNulls) { + this.ignoreNulls = ignoreNulls; + return this; + } + + public Boolean getIgnoreNulls() { + return ignoreNulls; + } + public LastDistinctFunction setInput(String input) { this.input = input; return this; @@ -41,16 +54,22 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LastDistinctFunction that = (LastDistinctFunction) o; - return Objects.equals(input, that.input) && Objects.equals(n, that.n); + return Objects.equals(ignoreNulls, that.ignoreNulls) + && Objects.equals(input, that.input) + && Objects.equals(n, that.n); } @Override public int hashCode() { - return Objects.hash(input, n); + return Objects.hash(ignoreNulls, input, n); } @Override public String toString() { - return new ToStringer(LastDistinctFunction.class).add("input", input).add("n", n).toString(); + return new ToStringer(LastDistinctFunction.class) + .add("ignoreNulls", ignoreNulls) + .add("input", input) + .add("n", n) + .toString(); } } diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LastFunction.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LastFunction.java index dd09f25bf..c820b0f9a 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LastFunction.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LastFunction.java @@ -10,10 +10,23 @@ /** Returns the last value. */ @Generated public class LastFunction { + /** When true, rows whose input is NULL are skipped. */ + @JsonProperty("ignore_nulls") + private Boolean ignoreNulls; + /** The input column from which the last value is returned. */ @JsonProperty("input") private String input; + public LastFunction setIgnoreNulls(Boolean ignoreNulls) { + this.ignoreNulls = ignoreNulls; + return this; + } + + public Boolean getIgnoreNulls() { + return ignoreNulls; + } + public LastFunction setInput(String input) { this.input = input; return this; @@ -28,16 +41,19 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LastFunction that = (LastFunction) o; - return Objects.equals(input, that.input); + return Objects.equals(ignoreNulls, that.ignoreNulls) && Objects.equals(input, that.input); } @Override public int hashCode() { - return Objects.hash(input); + return Objects.hash(ignoreNulls, input); } @Override public String toString() { - return new ToStringer(LastFunction.class).add("input", input).toString(); + return new ToStringer(LastFunction.class) + .add("ignoreNulls", ignoreNulls) + .add("input", input) + .toString(); } } diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LastNFunction.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LastNFunction.java index 715457468..c6f1419d5 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LastNFunction.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LastNFunction.java @@ -10,6 +10,10 @@ /** Returns the last N values, ordered by the feature's timeseries column. */ @Generated public class LastNFunction { + /** When true, rows whose input is NULL are skipped. */ + @JsonProperty("ignore_nulls") + private Boolean ignoreNulls; + /** The input column from which the last N values are returned. */ @JsonProperty("input") private String input; @@ -18,6 +22,15 @@ public class LastNFunction { @JsonProperty("n") private Long n; + public LastNFunction setIgnoreNulls(Boolean ignoreNulls) { + this.ignoreNulls = ignoreNulls; + return this; + } + + public Boolean getIgnoreNulls() { + return ignoreNulls; + } + public LastNFunction setInput(String input) { this.input = input; return this; @@ -41,16 +54,22 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LastNFunction that = (LastNFunction) o; - return Objects.equals(input, that.input) && Objects.equals(n, that.n); + return Objects.equals(ignoreNulls, that.ignoreNulls) + && Objects.equals(input, that.input) + && Objects.equals(n, that.n); } @Override public int hashCode() { - return Objects.hash(input, n); + return Objects.hash(ignoreNulls, input, n); } @Override public String toString() { - return new ToStringer(LastNFunction.class).add("input", input).add("n", n).toString(); + return new ToStringer(LastNFunction.class) + .add("ignoreNulls", ignoreNulls) + .add("input", input) + .add("n", n) + .toString(); } } diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LoggedModel.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LoggedModel.java index 5a57b30c2..1a8ea94d1 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LoggedModel.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LoggedModel.java @@ -8,8 +8,7 @@ import java.util.Objects; /** - * A logged model message includes logged model attributes, tags, registration info, params, and - * linked run metrics. + * A logged model message includes logged model attributes, tags, params, and linked run metrics. */ @Generated public class LoggedModel { diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LoggedModelInfo.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LoggedModelInfo.java index e6f626243..3e758ec08 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LoggedModelInfo.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/LoggedModelInfo.java @@ -8,7 +8,7 @@ import java.util.Collection; import java.util.Objects; -/** A LoggedModelInfo includes logged model attributes, tags, and registration info. */ +/** A LoggedModelInfo includes logged model attributes and tags. */ @Generated public class LoggedModelInfo { /** The URI of the directory where model artifacts are stored. */ diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/MaterializationFailureNotification.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/MaterializationFailureNotification.java index d02515535..3ceb2fa44 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/MaterializationFailureNotification.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/MaterializationFailureNotification.java @@ -22,21 +22,6 @@ public class MaterializationFailureNotification { @JsonProperty("email_addresses") private Collection emailAddresses; - /** - * If true, notify only when the final attempt of a run fails. If false or unset, notify on every - * failed attempt, including attempts that will be retried. - * - *

Batch materialization does not retry failures that need a fix on your side, such as missing - * permissions or invalid configuration, so the first attempt is the final one. Other batch - * failures are retried up to twice. - * - *

Streaming materialization restarts a failed update indefinitely unless the error cannot be - * retried. With this set, a streaming materialized feature notifies only on errors that cannot be - * retried, and never on failures that are restarted. - */ - @JsonProperty("final_attempt_only") - private Boolean finalAttemptOnly; - public MaterializationFailureNotification setDestinationIds(Collection destinationIds) { this.destinationIds = destinationIds; return this; @@ -55,28 +40,18 @@ public Collection getEmailAddresses() { return emailAddresses; } - public MaterializationFailureNotification setFinalAttemptOnly(Boolean finalAttemptOnly) { - this.finalAttemptOnly = finalAttemptOnly; - return this; - } - - public Boolean getFinalAttemptOnly() { - return finalAttemptOnly; - } - @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MaterializationFailureNotification that = (MaterializationFailureNotification) o; return Objects.equals(destinationIds, that.destinationIds) - && Objects.equals(emailAddresses, that.emailAddresses) - && Objects.equals(finalAttemptOnly, that.finalAttemptOnly); + && Objects.equals(emailAddresses, that.emailAddresses); } @Override public int hashCode() { - return Objects.hash(destinationIds, emailAddresses, finalAttemptOnly); + return Objects.hash(destinationIds, emailAddresses); } @Override @@ -84,7 +59,6 @@ public String toString() { return new ToStringer(MaterializationFailureNotification.class) .add("destinationIds", destinationIds) .add("emailAddresses", emailAddresses) - .add("finalAttemptOnly", finalAttemptOnly) .toString(); } } diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/MaterializationNotifications.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/MaterializationNotifications.java index 3fee31d68..93b556039 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/MaterializationNotifications.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/MaterializationNotifications.java @@ -10,7 +10,7 @@ /** Notifications for the jobs and pipelines that materialize features, one field per trigger. */ @Generated public class MaterializationNotifications { - /** Who to notify when a run fails, and on which attempts. */ + /** Who to notify when a run fails. */ @JsonProperty("on_failure") private MaterializationFailureNotification onFailure; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/MaterializationSetTriggerProgress.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/MaterializationSetTriggerProgress.java index 3e687542e..f12e34738 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/MaterializationSetTriggerProgress.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/MaterializationSetTriggerProgress.java @@ -9,8 +9,9 @@ import java.util.Objects; /** - * Progress and outcomes of the runs requested by `TriggerMaterializationSet`. Entries remain - * available after the operation finishes. + * Progress and outcomes of the runs requested by `TriggerMaterializationSet`. Run outcomes are read + * from Jobs, including after the operation finishes. If Jobs no longer provides a run's status, + * reading the operation returns a status-read error. * *

Once all requested runs have finished, the operation fails if any run failed. Otherwise, it is * cancelled if any run was cancelled, and succeeds if all runs succeeded. diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/SawtoothWindow.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/SawtoothWindow.java index ef201d064..d46950a92 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/SawtoothWindow.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/SawtoothWindow.java @@ -22,10 +22,10 @@ public class SawtoothWindow { private Duration delay; /** - * The duration of the window. Must be positive and span more than two days when set, so that both - * the batch (N-1 day) and stale-path (N-2 day) partial aggregates are well defined. The duration - * need not be a whole number of days (e.g. 3 days 15 minutes is allowed). Absent means lifetime - * (aggregate over the entity's entire history). + * The duration of the window. Must be positive and span more than twice the step (two days at the + * default 24h step) when set, so that both the batch (N-1 day) and stale-path (N-2 day) partial + * aggregates are well defined. The duration need not be a whole number of days (e.g. 3 days 15 + * minutes is allowed). Absent means lifetime (aggregate over the entity's entire history). */ @JsonProperty("window_duration") private Duration windowDuration; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/TriggerMaterializationSetRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/TriggerMaterializationSetRequest.java index a5330aff8..e0c205cc7 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/TriggerMaterializationSetRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/ml/TriggerMaterializationSetRequest.java @@ -17,7 +17,8 @@ public class TriggerMaterializationSetRequest { /** * Idempotency token in UUID format. Reusing it returns the original operation without starting * additional runs, even if the request differs or the operation has finished. If omitted, each - * request triggers independently. + * request triggers independently. Supply a token to recover an uncertain submission by retrying + * with the same request_id; requests without one cannot resume it. */ @JsonProperty("request_id") private String requestId; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/GenerateDatabaseCredentialRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/GenerateDatabaseCredentialRequest.java index 989f08894..fe7dd2427 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/GenerateDatabaseCredentialRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/GenerateDatabaseCredentialRequest.java @@ -12,13 +12,18 @@ @Generated public class GenerateDatabaseCredentialRequest { - /** The returned token will be scoped to UC tables with the specified permissions. */ + /** + * The returned token will be scoped to UC tables with the specified permissions. A token that + * carries claims cannot connect through the built-in connection pooler, so it needs a direct + * connection to the endpoint. + */ @JsonProperty("claims") private Collection claims; /** * The endpoint resource name for which this credential will be generated. Format: - * projects/{project_id}/branches/{branch_id}/endpoints/{endpoint_id} + * projects/{project_id}/branches/{branch_id}/endpoints/{endpoint_id} The endpoint must exist in + * the caller's workspace. */ @JsonProperty("endpoint") private String endpoint; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/ListProjectsRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/ListProjectsRequest.java index 492e1934b..b22396256 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/ListProjectsRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/ListProjectsRequest.java @@ -11,8 +11,11 @@ @Generated public class ListProjectsRequest { /** - * Upper bound for the number of projects returned. Cannot be negative. Values above the maximum - * page size are reduced to that maximum. + * The requested number of projects in one page. Cannot be negative. If not set or 0, the default + * is 10. A value above 100 is lowered to 100 without an error. A page can contain fewer projects, + * or none, while `next_page_token` is set; keep reading pages until `next_page_token` is empty. A + * page can contain more projects than this number when several projects were created at the same + * time. */ @JsonIgnore @QueryParam("page_size") diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/PostgresAPI.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/PostgresAPI.java index d0cacab32..d84a4e0ef 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/PostgresAPI.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/PostgresAPI.java @@ -279,7 +279,13 @@ public DeleteSyncedTableOperation deleteSyncedTable(DeleteSyncedTableRequest req return new DeleteSyncedTableOperation(impl, operation); } - /** Generate OAuth credentials for a Postgres database. */ + /** + * Generates a short-lived OAuth token for connecting to a Postgres endpoint. Use the token as the + * password and the caller's Databricks identity as the user name. The identity must have a + * corresponding Postgres role. When the request sets no expiration, the token expires after one + * hour. For connection steps, see + * https://docs.databricks.com/aws/en/oltp/projects/authentication. + */ public DatabaseCredential generateDatabaseCredential(GenerateDatabaseCredentialRequest request) { return impl.generateDatabaseCredential(request); } @@ -381,7 +387,13 @@ public Operation getOperation(String name) { return getOperation(new GetOperationRequest().setName(name)); } - /** Retrieves the status of a long-running operation. */ + /** + * Retrieves the status of a long-running operation. Methods that create, update or delete + * Postgres resources, such as projects, branches and endpoints, return an operation. Pass the + * full operation name that such a call returned. While the operation runs, done is false. When it + * finishes, done is true and either response holds the result of the method or error explains why + * the operation failed or was cancelled. + */ public Operation getOperation(GetOperationRequest request) { return impl.getOperation(request); } diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/PostgresService.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/PostgresService.java index 416e956bc..cd6a09e90 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/PostgresService.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/PostgresService.java @@ -149,7 +149,13 @@ Operation acknowledgeAssessmentWarnings( */ Operation deleteSyncedTable(DeleteSyncedTableRequest deleteSyncedTableRequest); - /** Generate OAuth credentials for a Postgres database. */ + /** + * Generates a short-lived OAuth token for connecting to a Postgres endpoint. Use the token as the + * password and the caller's Databricks identity as the user name. The identity must have a + * corresponding Postgres role. When the request sets no expiration, the token expires after one + * hour. For connection steps, see + * https://docs.databricks.com/aws/en/oltp/projects/authentication. + */ DatabaseCredential generateDatabaseCredential( GenerateDatabaseCredentialRequest generateDatabaseCredentialRequest); @@ -192,7 +198,13 @@ DatabaseCredential generateDatabaseCredential( /** Gets a migration. */ Migration getMigration(GetMigrationRequest getMigrationRequest); - /** Retrieves the status of a long-running operation. */ + /** + * Retrieves the status of a long-running operation. Methods that create, update or delete + * Postgres resources, such as projects, branches and endpoints, return an operation. Pass the + * full operation name that such a call returned. While the operation runs, done is false. When it + * finishes, done is true and either response holds the result of the method or error explains why + * the operation failed or was cancelled. + */ Operation getOperation(GetOperationRequest getOperationRequest); /** Retrieves information about the specified database project. */ diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/RequestedClaims.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/RequestedClaims.java index 60ce0c5c6..1e483859a 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/RequestedClaims.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/RequestedClaims.java @@ -10,11 +10,14 @@ @Generated public class RequestedClaims { - /** */ + /** + * The level of access that the credential grants on the listed resources. READ_ONLY covers SELECT + * on each table, along with USE SCHEMA on its schema and USE CATALOG on its catalog. + */ @JsonProperty("permission_set") private RequestedClaimsPermissionSet permissionSet; - /** */ + /** The Unity Catalog tables that the permission set applies to. */ @JsonProperty("resources") private Collection resources; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/RequestedResource.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/RequestedResource.java index ee195b8a2..36a18263e 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/RequestedResource.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/postgres/RequestedResource.java @@ -9,7 +9,7 @@ @Generated public class RequestedResource { - /** The full Unity Catalog table name. */ + /** The full three-level Unity Catalog name of the table, in the form catalog.schema.table. */ @JsonProperty("table_name") private String tableName; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sandbox/ComputeSpec.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sandbox/ComputeSpec.java index 0186817f2..c3068feb2 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sandbox/ComputeSpec.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sandbox/ComputeSpec.java @@ -10,6 +10,16 @@ @Generated public class ComputeSpec { + /** + * Requested vCPUs, for example 8. If this is unset and memory_mib is set, the sandbox gets one + * vCPU per 4096 MiB. Currently, CPU must be a whole number and CPU and memory must match a + * supported regional configuration at this ratio. Supported only for Lakebox MicroVM sandboxes. + * Cannot be combined with sandbox_size. Both fields are create-only. Reads return both resolved + * values for explicitly sized sandboxes. + */ + @JsonProperty("cpu") + private Double cpu; + /** * Idle time after which the sandbox is automatically stopped. Unset or 0 disables inactivity * auto-stop. Negative values are rejected. Can be changed on an existing sandbox with @@ -18,6 +28,22 @@ public class ComputeSpec { @JsonProperty("inactivity_timeout") private Duration inactivityTimeout; + /** + * Requested memory in MiB. If this is unset and cpu is set, the sandbox gets 4096 MiB per vCPU. + * The same restrictions apply as for cpu. + */ + @JsonProperty("memory_mib") + private Long memoryMib; + + public ComputeSpec setCpu(Double cpu) { + this.cpu = cpu; + return this; + } + + public Double getCpu() { + return cpu; + } + public ComputeSpec setInactivityTimeout(Duration inactivityTimeout) { this.inactivityTimeout = inactivityTimeout; return this; @@ -27,21 +53,36 @@ public Duration getInactivityTimeout() { return inactivityTimeout; } + public ComputeSpec setMemoryMib(Long memoryMib) { + this.memoryMib = memoryMib; + return this; + } + + public Long getMemoryMib() { + return memoryMib; + } + @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ComputeSpec that = (ComputeSpec) o; - return Objects.equals(inactivityTimeout, that.inactivityTimeout); + return Objects.equals(cpu, that.cpu) + && Objects.equals(inactivityTimeout, that.inactivityTimeout) + && Objects.equals(memoryMib, that.memoryMib); } @Override public int hashCode() { - return Objects.hash(inactivityTimeout); + return Objects.hash(cpu, inactivityTimeout, memoryMib); } @Override public String toString() { - return new ToStringer(ComputeSpec.class).add("inactivityTimeout", inactivityTimeout).toString(); + return new ToStringer(ComputeSpec.class) + .add("cpu", cpu) + .add("inactivityTimeout", inactivityTimeout) + .add("memoryMib", memoryMib) + .toString(); } } diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sandbox/SandboxSpec.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sandbox/SandboxSpec.java index b4e42f874..5f5076c30 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sandbox/SandboxSpec.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sandbox/SandboxSpec.java @@ -21,6 +21,10 @@ public class SandboxSpec { @JsonProperty("network") private NetworkSpec network; + /** Persistence configuration requested for the sandbox at creation time. */ + @JsonProperty("storage") + private StorageSpec storage; + public SandboxSpec setCompute(ComputeSpec compute) { this.compute = compute; return this; @@ -48,6 +52,15 @@ public NetworkSpec getNetwork() { return network; } + public SandboxSpec setStorage(StorageSpec storage) { + this.storage = storage; + return this; + } + + public StorageSpec getStorage() { + return storage; + } + @Override public boolean equals(Object o) { if (this == o) return true; @@ -55,12 +68,13 @@ public boolean equals(Object o) { SandboxSpec that = (SandboxSpec) o; return Objects.equals(compute, that.compute) && Objects.equals(environment, that.environment) - && Objects.equals(network, that.network); + && Objects.equals(network, that.network) + && Objects.equals(storage, that.storage); } @Override public int hashCode() { - return Objects.hash(compute, environment, network); + return Objects.hash(compute, environment, network, storage); } @Override @@ -69,6 +83,7 @@ public String toString() { .add("compute", compute) .add("environment", environment) .add("network", network) + .add("storage", storage) .toString(); } } diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sandbox/StorageSpec.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sandbox/StorageSpec.java new file mode 100644 index 000000000..f2a17c34f --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sandbox/StorageSpec.java @@ -0,0 +1,50 @@ +// Code generated from OpenAPI specs by Databricks SDK Generator. DO NOT EDIT. + +package com.databricks.sdk.service.sandbox; + +import com.databricks.sdk.support.Generated; +import com.databricks.sdk.support.ToStringer; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Objects; + +/** Storage configuration for the sandbox. */ +@Generated +public class StorageSpec { + /** + * Whether sandbox files persist across stop and start. If omitted, the service selects a default + * for the workspace and sandbox creator. This setting is fixed when the sandbox is created. When + * false, no persistent volume is allocated, and StopSandbox and StartSandbox are unavailable. Use + * CreateSandbox and DeleteSandbox for these sandboxes. + */ + @JsonProperty("persistence_enabled") + private Boolean persistenceEnabled; + + public StorageSpec setPersistenceEnabled(Boolean persistenceEnabled) { + this.persistenceEnabled = persistenceEnabled; + return this; + } + + public Boolean getPersistenceEnabled() { + return persistenceEnabled; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + StorageSpec that = (StorageSpec) o; + return Objects.equals(persistenceEnabled, that.persistenceEnabled); + } + + @Override + public int hashCode() { + return Objects.hash(persistenceEnabled); + } + + @Override + public String toString() { + return new ToStringer(StorageSpec.class) + .add("persistenceEnabled", persistenceEnabled) + .toString(); + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/serving/TelemetryConfig.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/serving/TelemetryConfig.java index 60a69ad43..c9b2785cf 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/serving/TelemetryConfig.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/serving/TelemetryConfig.java @@ -11,8 +11,8 @@ @Generated public class TelemetryConfig { /** - * The telemetry signals to enable for this endpoint. If empty or omitted, all signals are - * enabled; otherwise only the listed signals are enabled. + * The telemetry signals to enable for this endpoint. If empty or omitted, all signals except + * opt-in ones are enabled; otherwise only the listed signals are enabled. */ @JsonProperty("enabled_telemetry_features") private Collection enabledTelemetryFeatures; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/AsanaConfig.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/AsanaConfig.java new file mode 100644 index 000000000..a9408b992 --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/AsanaConfig.java @@ -0,0 +1,97 @@ +// Code generated from OpenAPI specs by Databricks SDK Generator. DO NOT EDIT. + +package com.databricks.sdk.service.settings; + +import com.databricks.sdk.support.Generated; +import com.databricks.sdk.support.ToStringer; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Objects; + +/** + * Configures an Asana destination. Each notification either creates a task in a project or runs an + * Asana rule. Databricks authenticates with an Asana personal access token, so the token's user + * needs access to the project, rule and task. + */ +@Generated +public class AsanaConfig { + /** + * [Input-Only] Asana personal access token used to authenticate notifications. Use a token from a + * dedicated Asana user that can access only the target project, rule and task. + */ + @JsonProperty("personal_access_token") + private String personalAccessToken; + + /** [Output-Only] Whether personal access token is set. */ + @JsonProperty("personal_access_token_set") + private Boolean personalAccessTokenSet; + + /** Runs an existing Asana rule for each notification. */ + @JsonProperty("rule_trigger") + private AsanaRuleTriggerTarget ruleTrigger; + + /** Creates a task in an Asana project for each notification. */ + @JsonProperty("task_creation") + private AsanaTaskCreationTarget taskCreation; + + public AsanaConfig setPersonalAccessToken(String personalAccessToken) { + this.personalAccessToken = personalAccessToken; + return this; + } + + public String getPersonalAccessToken() { + return personalAccessToken; + } + + public AsanaConfig setPersonalAccessTokenSet(Boolean personalAccessTokenSet) { + this.personalAccessTokenSet = personalAccessTokenSet; + return this; + } + + public Boolean getPersonalAccessTokenSet() { + return personalAccessTokenSet; + } + + public AsanaConfig setRuleTrigger(AsanaRuleTriggerTarget ruleTrigger) { + this.ruleTrigger = ruleTrigger; + return this; + } + + public AsanaRuleTriggerTarget getRuleTrigger() { + return ruleTrigger; + } + + public AsanaConfig setTaskCreation(AsanaTaskCreationTarget taskCreation) { + this.taskCreation = taskCreation; + return this; + } + + public AsanaTaskCreationTarget getTaskCreation() { + return taskCreation; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + AsanaConfig that = (AsanaConfig) o; + return Objects.equals(personalAccessToken, that.personalAccessToken) + && Objects.equals(personalAccessTokenSet, that.personalAccessTokenSet) + && Objects.equals(ruleTrigger, that.ruleTrigger) + && Objects.equals(taskCreation, that.taskCreation); + } + + @Override + public int hashCode() { + return Objects.hash(personalAccessToken, personalAccessTokenSet, ruleTrigger, taskCreation); + } + + @Override + public String toString() { + return new ToStringer(AsanaConfig.class) + .add("personalAccessToken", personalAccessToken) + .add("personalAccessTokenSet", personalAccessTokenSet) + .add("ruleTrigger", ruleTrigger) + .add("taskCreation", taskCreation) + .toString(); + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/AsanaRuleTriggerTarget.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/AsanaRuleTriggerTarget.java new file mode 100644 index 000000000..813ba23a2 --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/AsanaRuleTriggerTarget.java @@ -0,0 +1,67 @@ +// Code generated from OpenAPI specs by Databricks SDK Generator. DO NOT EDIT. + +package com.databricks.sdk.service.settings; + +import com.databricks.sdk.support.Generated; +import com.databricks.sdk.support.ToStringer; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Objects; + +/** + * Asana rule that an Asana destination runs for each notification. The rule must have an incoming + * web request trigger. Retries can run the rule again, so its actions should handle repeated + * notifications. + */ +@Generated +public class AsanaRuleTriggerTarget { + /** + * Numeric ID of an existing task that the rule runs against. Asana requires one even when the + * rule's actions don't use it. + */ + @JsonProperty("anchor_task_gid") + private String anchorTaskGid; + + /** Numeric ID of the rule's incoming web request trigger. */ + @JsonProperty("rule_trigger_gid") + private String ruleTriggerGid; + + public AsanaRuleTriggerTarget setAnchorTaskGid(String anchorTaskGid) { + this.anchorTaskGid = anchorTaskGid; + return this; + } + + public String getAnchorTaskGid() { + return anchorTaskGid; + } + + public AsanaRuleTriggerTarget setRuleTriggerGid(String ruleTriggerGid) { + this.ruleTriggerGid = ruleTriggerGid; + return this; + } + + public String getRuleTriggerGid() { + return ruleTriggerGid; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + AsanaRuleTriggerTarget that = (AsanaRuleTriggerTarget) o; + return Objects.equals(anchorTaskGid, that.anchorTaskGid) + && Objects.equals(ruleTriggerGid, that.ruleTriggerGid); + } + + @Override + public int hashCode() { + return Objects.hash(anchorTaskGid, ruleTriggerGid); + } + + @Override + public String toString() { + return new ToStringer(AsanaRuleTriggerTarget.class) + .add("anchorTaskGid", anchorTaskGid) + .add("ruleTriggerGid", ruleTriggerGid) + .toString(); + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/AsanaTaskCreationTarget.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/AsanaTaskCreationTarget.java new file mode 100644 index 000000000..6782c9dfa --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/AsanaTaskCreationTarget.java @@ -0,0 +1,46 @@ +// Code generated from OpenAPI specs by Databricks SDK Generator. DO NOT EDIT. + +package com.databricks.sdk.service.settings; + +import com.databricks.sdk.support.Generated; +import com.databricks.sdk.support.ToStringer; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Objects; + +/** + * Asana project that an Asana destination adds a task to for each notification. The task's title + * and notes are derived from the notification. + */ +@Generated +public class AsanaTaskCreationTarget { + /** Numeric ID of the Asana project. */ + @JsonProperty("project_gid") + private String projectGid; + + public AsanaTaskCreationTarget setProjectGid(String projectGid) { + this.projectGid = projectGid; + return this; + } + + public String getProjectGid() { + return projectGid; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + AsanaTaskCreationTarget that = (AsanaTaskCreationTarget) o; + return Objects.equals(projectGid, that.projectGid); + } + + @Override + public int hashCode() { + return Objects.hash(projectGid); + } + + @Override + public String toString() { + return new ToStringer(AsanaTaskCreationTarget.class).add("projectGid", projectGid).toString(); + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/Config.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/Config.java index 2c6405a3f..691253aa2 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/Config.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/Config.java @@ -10,6 +10,10 @@ /** Holds the destination-specific configuration. Exactly one of the nested configs is set. */ @Generated public class Config { + /** Configures an Asana destination. */ + @JsonProperty("asana") + private AsanaConfig asana; + /** Configures a Slack channel reached through the Databricks Genie app for Slack. */ @JsonProperty("databricks_app_slack") private DatabricksAppSlackConfig databricksAppSlack; @@ -37,10 +41,23 @@ public class Config { @JsonProperty("pagerduty") private PagerdutyConfig pagerduty; + /** Configures a ServiceNow destination. */ + @JsonProperty("service_now") + private ServiceNowConfig serviceNow; + /** Configures a Slack incoming webhook destination. */ @JsonProperty("slack") private SlackConfig slack; + public Config setAsana(AsanaConfig asana) { + this.asana = asana; + return this; + } + + public AsanaConfig getAsana() { + return asana; + } + public Config setDatabricksAppSlack(DatabricksAppSlackConfig databricksAppSlack) { this.databricksAppSlack = databricksAppSlack; return this; @@ -95,6 +112,15 @@ public PagerdutyConfig getPagerduty() { return pagerduty; } + public Config setServiceNow(ServiceNowConfig serviceNow) { + this.serviceNow = serviceNow; + return this; + } + + public ServiceNowConfig getServiceNow() { + return serviceNow; + } + public Config setSlack(SlackConfig slack) { this.slack = slack; return this; @@ -109,36 +135,42 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Config that = (Config) o; - return Objects.equals(databricksAppSlack, that.databricksAppSlack) + return Objects.equals(asana, that.asana) + && Objects.equals(databricksAppSlack, that.databricksAppSlack) && Objects.equals(databricksAppTeams, that.databricksAppTeams) && Objects.equals(email, that.email) && Objects.equals(genericWebhook, that.genericWebhook) && Objects.equals(microsoftTeams, that.microsoftTeams) && Objects.equals(pagerduty, that.pagerduty) + && Objects.equals(serviceNow, that.serviceNow) && Objects.equals(slack, that.slack); } @Override public int hashCode() { return Objects.hash( + asana, databricksAppSlack, databricksAppTeams, email, genericWebhook, microsoftTeams, pagerduty, + serviceNow, slack); } @Override public String toString() { return new ToStringer(Config.class) + .add("asana", asana) .add("databricksAppSlack", databricksAppSlack) .add("databricksAppTeams", databricksAppTeams) .add("email", email) .add("genericWebhook", genericWebhook) .add("microsoftTeams", microsoftTeams) .add("pagerduty", pagerduty) + .add("serviceNow", serviceNow) .add("slack", slack) .toString(); } diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/CreateOboTokenRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/CreateOboTokenRequest.java index 4362630f8..07a491788 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/CreateOboTokenRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/CreateOboTokenRequest.java @@ -30,7 +30,7 @@ public class CreateOboTokenRequest { @JsonProperty("lifetime_seconds") private Long lifetimeSeconds; - /** */ + /** Optional scopes of the token. */ @JsonProperty("scopes") private Collection scopes; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/CreateOboTokenResponse.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/CreateOboTokenResponse.java index 2b9157a11..d8a2ae774 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/CreateOboTokenResponse.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/CreateOboTokenResponse.java @@ -10,7 +10,7 @@ /** An on-behalf token was successfully created for the service principal. */ @Generated public class CreateOboTokenResponse { - /** */ + /** Metadata of the created token. Does not include the token value. */ @JsonProperty("token_info") private TokenInfo tokenInfo; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/DestinationType.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/DestinationType.java index 2ff781d5b..3f73289c6 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/DestinationType.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/DestinationType.java @@ -7,11 +7,13 @@ /** The kind of destination that notifications are sent to. */ @Generated public enum DestinationType { + ASANA, DATABRICKS_APP_SLACK, DATABRICKS_APP_TEAMS, EMAIL, MICROSOFT_TEAMS, PAGERDUTY, + SERVICE_NOW, SLACK, WEBHOOK, } diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/ServiceNowConfig.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/ServiceNowConfig.java new file mode 100644 index 000000000..1b41beb6a --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/ServiceNowConfig.java @@ -0,0 +1,184 @@ +// Code generated from OpenAPI specs by Databricks SDK Generator. DO NOT EDIT. + +package com.databricks.sdk.service.settings; + +import com.databricks.sdk.support.Generated; +import com.databricks.sdk.support.ToStringer; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Objects; + +/** + * Configures a ServiceNow destination. Notifications are posted as records to the table at url + * through the ServiceNow Table API. Databricks authenticates with an access token that it obtains + * from oauth_token_url using the OAuth 2.0 client credentials grant. + */ +@Generated +public class ServiceNowConfig { + /** [Input-Only] OAuth 2.0 client ID of the ServiceNow OAuth application. */ + @JsonProperty("oauth_client_id") + private String oauthClientId; + + /** [Output-Only] Whether OAuth client ID is set. */ + @JsonProperty("oauth_client_id_set") + private Boolean oauthClientIdSet; + + /** [Input-Only] OAuth 2.0 client secret of the ServiceNow OAuth application. */ + @JsonProperty("oauth_client_secret") + private String oauthClientSecret; + + /** [Output-Only] Whether OAuth client secret is set. */ + @JsonProperty("oauth_client_secret_set") + private Boolean oauthClientSecretSet; + + /** + * [Input-Only] HTTPS token endpoint of the ServiceNow OAuth application. Must not contain + * credentials. + */ + @JsonProperty("oauth_token_url") + private String oauthTokenUrl; + + /** [Output-Only] Whether OAuth token URL is set. */ + @JsonProperty("oauth_token_url_set") + private Boolean oauthTokenUrlSet; + + /** Scope of the table at url. Unset means application-scoped. */ + @JsonProperty("table_scope") + private ServiceNowTableScope tableScope; + + /** + * [Input-Only] HTTPS Table API URL of the table that receives the records. Must not contain + * credentials. + */ + @JsonProperty("url") + private String url; + + /** [Output-Only] Whether URL is set. */ + @JsonProperty("url_set") + private Boolean urlSet; + + public ServiceNowConfig setOauthClientId(String oauthClientId) { + this.oauthClientId = oauthClientId; + return this; + } + + public String getOauthClientId() { + return oauthClientId; + } + + public ServiceNowConfig setOauthClientIdSet(Boolean oauthClientIdSet) { + this.oauthClientIdSet = oauthClientIdSet; + return this; + } + + public Boolean getOauthClientIdSet() { + return oauthClientIdSet; + } + + public ServiceNowConfig setOauthClientSecret(String oauthClientSecret) { + this.oauthClientSecret = oauthClientSecret; + return this; + } + + public String getOauthClientSecret() { + return oauthClientSecret; + } + + public ServiceNowConfig setOauthClientSecretSet(Boolean oauthClientSecretSet) { + this.oauthClientSecretSet = oauthClientSecretSet; + return this; + } + + public Boolean getOauthClientSecretSet() { + return oauthClientSecretSet; + } + + public ServiceNowConfig setOauthTokenUrl(String oauthTokenUrl) { + this.oauthTokenUrl = oauthTokenUrl; + return this; + } + + public String getOauthTokenUrl() { + return oauthTokenUrl; + } + + public ServiceNowConfig setOauthTokenUrlSet(Boolean oauthTokenUrlSet) { + this.oauthTokenUrlSet = oauthTokenUrlSet; + return this; + } + + public Boolean getOauthTokenUrlSet() { + return oauthTokenUrlSet; + } + + public ServiceNowConfig setTableScope(ServiceNowTableScope tableScope) { + this.tableScope = tableScope; + return this; + } + + public ServiceNowTableScope getTableScope() { + return tableScope; + } + + public ServiceNowConfig setUrl(String url) { + this.url = url; + return this; + } + + public String getUrl() { + return url; + } + + public ServiceNowConfig setUrlSet(Boolean urlSet) { + this.urlSet = urlSet; + return this; + } + + public Boolean getUrlSet() { + return urlSet; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ServiceNowConfig that = (ServiceNowConfig) o; + return Objects.equals(oauthClientId, that.oauthClientId) + && Objects.equals(oauthClientIdSet, that.oauthClientIdSet) + && Objects.equals(oauthClientSecret, that.oauthClientSecret) + && Objects.equals(oauthClientSecretSet, that.oauthClientSecretSet) + && Objects.equals(oauthTokenUrl, that.oauthTokenUrl) + && Objects.equals(oauthTokenUrlSet, that.oauthTokenUrlSet) + && Objects.equals(tableScope, that.tableScope) + && Objects.equals(url, that.url) + && Objects.equals(urlSet, that.urlSet); + } + + @Override + public int hashCode() { + return Objects.hash( + oauthClientId, + oauthClientIdSet, + oauthClientSecret, + oauthClientSecretSet, + oauthTokenUrl, + oauthTokenUrlSet, + tableScope, + url, + urlSet); + } + + @Override + public String toString() { + return new ToStringer(ServiceNowConfig.class) + .add("oauthClientId", oauthClientId) + .add("oauthClientIdSet", oauthClientIdSet) + .add("oauthClientSecret", oauthClientSecret) + .add("oauthClientSecretSet", oauthClientSecretSet) + .add("oauthTokenUrl", oauthTokenUrl) + .add("oauthTokenUrlSet", oauthTokenUrlSet) + .add("tableScope", tableScope) + .add("url", url) + .add("urlSet", urlSet) + .toString(); + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/ServiceNowTableScope.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/ServiceNowTableScope.java new file mode 100644 index 000000000..f145f60bf --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settings/ServiceNowTableScope.java @@ -0,0 +1,12 @@ +// Code generated from OpenAPI specs by Databricks SDK Generator. DO NOT EDIT. + +package com.databricks.sdk.service.settings; + +import com.databricks.sdk.support.Generated; + +/** Scope of the ServiceNow table that a ServiceNow destination posts records to. */ +@Generated +public enum ServiceNowTableScope { + SERVICE_NOW_TABLE_SCOPE_APPLICATION, + SERVICE_NOW_TABLE_SCOPE_GLOBAL, +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/GetPublicAccountUserPreferenceRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/GetPublicAccountUserPreferenceRequest.java index 612f8b834..a84a0c53c 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/GetPublicAccountUserPreferenceRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/GetPublicAccountUserPreferenceRequest.java @@ -9,7 +9,7 @@ @Generated public class GetPublicAccountUserPreferenceRequest { - /** User Setting name. */ + /** Identifies the user preference to retrieve. */ @JsonIgnore private String name; /** User ID of the user whose setting is being retrieved. */ diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/PatchPublicAccountUserPreferenceRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/PatchPublicAccountUserPreferenceRequest.java index 9cb3ab371..508ff98cd 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/PatchPublicAccountUserPreferenceRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/PatchPublicAccountUserPreferenceRequest.java @@ -10,7 +10,10 @@ @Generated public class PatchPublicAccountUserPreferenceRequest { - /** */ + /** + * Identifies the user preference to update. The request body's `name` and `user_id` are ignored; + * the path parameters select the preference. + */ @JsonIgnore private String name; /** */ diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/ReposAllowListPermissionMessage.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/ReposAllowListPermissionMessage.java new file mode 100644 index 000000000..c1ce6f344 --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/ReposAllowListPermissionMessage.java @@ -0,0 +1,45 @@ +// Code generated from OpenAPI specs by Databricks SDK Generator. DO NOT EDIT. + +package com.databricks.sdk.service.settingsv2; + +import com.databricks.sdk.support.Generated; +import com.databricks.sdk.support.ToStringer; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Objects; + +@Generated +public class ReposAllowListPermissionMessage { + /** */ + @JsonProperty("permission") + private ReposAllowListPermissionMessagePermission permission; + + public ReposAllowListPermissionMessage setPermission( + ReposAllowListPermissionMessagePermission permission) { + this.permission = permission; + return this; + } + + public ReposAllowListPermissionMessagePermission getPermission() { + return permission; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ReposAllowListPermissionMessage that = (ReposAllowListPermissionMessage) o; + return Objects.equals(permission, that.permission); + } + + @Override + public int hashCode() { + return Objects.hash(permission); + } + + @Override + public String toString() { + return new ToStringer(ReposAllowListPermissionMessage.class) + .add("permission", permission) + .toString(); + } +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/ReposAllowListPermissionMessagePermission.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/ReposAllowListPermissionMessagePermission.java new file mode 100644 index 000000000..a597061b5 --- /dev/null +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/ReposAllowListPermissionMessagePermission.java @@ -0,0 +1,12 @@ +// Code generated from OpenAPI specs by Databricks SDK Generator. DO NOT EDIT. + +package com.databricks.sdk.service.settingsv2; + +import com.databricks.sdk.support.Generated; + +@Generated +public enum ReposAllowListPermissionMessagePermission { + ALLOWLISTED_CLONE_COMMIT_PUSH, + ALLOWLISTED_COMMIT_PUSH, + ALL_REPOS, +} diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/Setting.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/Setting.java index 818da5909..1c1eb9991 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/Setting.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/Setting.java @@ -124,6 +124,10 @@ public class Setting { @JsonProperty("effective_personal_compute") private PersonalComputeMessage effectivePersonalCompute; + /** Evaluated Git folder allowlist permission. To set a value, use repo_allowlist_permission. */ + @JsonProperty("effective_repo_allowlist_permission") + private ReposAllowListPermissionMessage effectiveRepoAllowlistPermission; + /** * Effective setting value for restrict_workspace_admins setting. This is the final effective * value of setting. To set a value use restrict_workspace_admins. @@ -179,6 +183,13 @@ public class Setting { @JsonProperty("personal_compute") private PersonalComputeMessage personalCompute; + /** + * Saved Git folder allowlist permission. Check effective_repo_allowlist_permission for the + * evaluated value. + */ + @JsonProperty("repo_allowlist_permission") + private ReposAllowListPermissionMessage repoAllowlistPermission; + /** * Setting value for restrict_workspace_admins setting. This is the setting value set by * consumers, check effective_restrict_workspace_admins for final setting value. @@ -354,6 +365,16 @@ public PersonalComputeMessage getEffectivePersonalCompute() { return effectivePersonalCompute; } + public Setting setEffectiveRepoAllowlistPermission( + ReposAllowListPermissionMessage effectiveRepoAllowlistPermission) { + this.effectiveRepoAllowlistPermission = effectiveRepoAllowlistPermission; + return this; + } + + public ReposAllowListPermissionMessage getEffectiveRepoAllowlistPermission() { + return effectiveRepoAllowlistPermission; + } + public Setting setEffectiveRestrictWorkspaceAdmins( RestrictWorkspaceAdminsMessage effectiveRestrictWorkspaceAdmins) { this.effectiveRestrictWorkspaceAdmins = effectiveRestrictWorkspaceAdmins; @@ -429,6 +450,16 @@ public PersonalComputeMessage getPersonalCompute() { return personalCompute; } + public Setting setRepoAllowlistPermission( + ReposAllowListPermissionMessage repoAllowlistPermission) { + this.repoAllowlistPermission = repoAllowlistPermission; + return this; + } + + public ReposAllowListPermissionMessage getRepoAllowlistPermission() { + return repoAllowlistPermission; + } + public Setting setRestrictWorkspaceAdmins( RestrictWorkspaceAdminsMessage restrictWorkspaceAdmins) { this.restrictWorkspaceAdmins = restrictWorkspaceAdmins; @@ -496,6 +527,7 @@ public boolean equals(Object o) { && Objects.equals( effectiveOperationalEmailCustomRecipient, that.effectiveOperationalEmailCustomRecipient) && Objects.equals(effectivePersonalCompute, that.effectivePersonalCompute) + && Objects.equals(effectiveRepoAllowlistPermission, that.effectiveRepoAllowlistPermission) && Objects.equals(effectiveRestrictWorkspaceAdmins, that.effectiveRestrictWorkspaceAdmins) && Objects.equals(effectiveStringVal, that.effectiveStringVal) && Objects.equals(effectiveWorkspaceDashboardTheme, that.effectiveWorkspaceDashboardTheme) @@ -504,6 +536,7 @@ public boolean equals(Object o) { && Objects.equals(name, that.name) && Objects.equals(operationalEmailCustomRecipient, that.operationalEmailCustomRecipient) && Objects.equals(personalCompute, that.personalCompute) + && Objects.equals(repoAllowlistPermission, that.repoAllowlistPermission) && Objects.equals(restrictWorkspaceAdmins, that.restrictWorkspaceAdmins) && Objects.equals(stringVal, that.stringVal) && Objects.equals(workspaceDashboardTheme, that.workspaceDashboardTheme) @@ -528,6 +561,7 @@ public int hashCode() { effectiveIntegerVal, effectiveOperationalEmailCustomRecipient, effectivePersonalCompute, + effectiveRepoAllowlistPermission, effectiveRestrictWorkspaceAdmins, effectiveStringVal, effectiveWorkspaceDashboardTheme, @@ -536,6 +570,7 @@ public int hashCode() { name, operationalEmailCustomRecipient, personalCompute, + repoAllowlistPermission, restrictWorkspaceAdmins, stringVal, workspaceDashboardTheme, @@ -566,6 +601,7 @@ public String toString() { .add("effectiveIntegerVal", effectiveIntegerVal) .add("effectiveOperationalEmailCustomRecipient", effectiveOperationalEmailCustomRecipient) .add("effectivePersonalCompute", effectivePersonalCompute) + .add("effectiveRepoAllowlistPermission", effectiveRepoAllowlistPermission) .add("effectiveRestrictWorkspaceAdmins", effectiveRestrictWorkspaceAdmins) .add("effectiveStringVal", effectiveStringVal) .add("effectiveWorkspaceDashboardTheme", effectiveWorkspaceDashboardTheme) @@ -574,6 +610,7 @@ public String toString() { .add("name", name) .add("operationalEmailCustomRecipient", operationalEmailCustomRecipient) .add("personalCompute", personalCompute) + .add("repoAllowlistPermission", repoAllowlistPermission) .add("restrictWorkspaceAdmins", restrictWorkspaceAdmins) .add("stringVal", stringVal) .add("workspaceDashboardTheme", workspaceDashboardTheme) diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/UserPreference.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/UserPreference.java index 4d13d93c6..fd6cbff42 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/UserPreference.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/settingsv2/UserPreference.java @@ -14,27 +14,42 @@ */ @Generated public class UserPreference { - /** */ + /** + * Holds the value that the user set for a boolean preference. Each preference uses either + * `boolean_val` or `string_val`, depending on its type. Responses omit the user-set value when + * the user has not set one. + */ @JsonProperty("boolean_val") private BooleanMessage booleanVal; - /** */ + /** + * Holds the value that takes effect for a boolean preference. The server evaluates it from the + * user-set value and the preference's policy, so it can differ from `boolean_val`. When the user + * has not set a value, it reflects the preference's default. + */ @JsonProperty("effective_boolean_val") private BooleanMessage effectiveBooleanVal; - /** */ + /** Holds the value that takes effect for a string preference, as evaluated by the server. */ @JsonProperty("effective_string_val") private StringMessage effectiveStringVal; - /** Name of the setting. */ + /** + * Identifies the user preference. The "List user preferences and their metadata" method returns + * the valid names. + */ @JsonProperty("name") private String name; - /** */ + /** Holds the value that the user set for a string preference. */ @JsonProperty("string_val") private StringMessage stringVal; - /** User ID of the user. */ + /** + * Identifies the user that the preference belongs to. The value is the numeric account user ID + * that the Account Users API (https://docs.databricks.com/api/account/accountusersv2/list) + * returns. + */ @JsonProperty("user_id") private String userId; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sql/DefaultWarehouseOverride.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sql/DefaultWarehouseOverride.java index e7e7f8320..a4fae820e 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sql/DefaultWarehouseOverride.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sql/DefaultWarehouseOverride.java @@ -14,13 +14,16 @@ */ @Generated public class DefaultWarehouseOverride { - /** The ID component of the resource name (user ID). */ + /** + * The numeric ID of the user that the override applies to. It is the last component of `name`. + */ @JsonProperty("default_warehouse_override_id") private String defaultWarehouseOverrideId; /** * The resource name of the default warehouse override. Format: - * default-warehouse-overrides/{default_warehouse_override_id} + * default-warehouse-overrides/{default_warehouse_override_id} Responses always contain the + * numeric user ID, even when the request used `me`. */ @JsonProperty("name") private String name; @@ -29,7 +32,11 @@ public class DefaultWarehouseOverride { @JsonProperty("type") private DefaultWarehouseOverrideType typeValue; - /** The specific warehouse ID when type is CUSTOM. Not set for LAST_SELECTED type. */ + /** + * The ID of the SQL warehouse to preselect when `type` is `CUSTOM`. It is required for `CUSTOM` + * and must be a valid warehouse ID. It is ignored for `LAST_SELECTED` and is not returned for + * that type. + */ @JsonProperty("warehouse_id") private String warehouseId; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sql/UpdateDefaultWarehouseOverrideRequest.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sql/UpdateDefaultWarehouseOverrideRequest.java index 592f62930..3559d2fd8 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sql/UpdateDefaultWarehouseOverrideRequest.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sql/UpdateDefaultWarehouseOverrideRequest.java @@ -13,8 +13,9 @@ @Generated public class UpdateDefaultWarehouseOverrideRequest { /** - * If set to true, and the override is not found, a new override will be created. In this - * situation, `update_mask` is ignored and all fields are applied. Defaults to false. + * If set to true, and the override is not found, a new override will be created. Whenever + * `allow_missing` is true, `update_mask` is ignored and all fields are applied, whether or not + * the override already exists. Defaults to false. */ @JsonIgnore @QueryParam("allow_missing") @@ -30,7 +31,8 @@ public class UpdateDefaultWarehouseOverrideRequest { /** * The resource name of the default warehouse override. Format: - * default-warehouse-overrides/{default_warehouse_override_id} + * default-warehouse-overrides/{default_warehouse_override_id} Responses always contain the + * numeric user ID, even when the request used `me`. */ @JsonIgnore private String name; diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sql/WarehousesAPI.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sql/WarehousesAPI.java index dbe33d02a..02c66c46d 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sql/WarehousesAPI.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sql/WarehousesAPI.java @@ -135,7 +135,8 @@ public Wait create( /** * Creates a new default warehouse override for a user. Users can create their own override. - * Admins can create overrides for any user. + * Admins can create overrides for any user. If the user already has an override, the request + * fails with `ALREADY_EXISTS`. */ public DefaultWarehouseOverride createDefaultWarehouseOverride( CreateDefaultWarehouseOverrideRequest request) { @@ -186,8 +187,8 @@ public DefaultWarehouseOverride getDefaultWarehouseOverride(String name) { /** * Returns the default warehouse override for a user. Users can fetch their own override. Admins - * can fetch overrides for any user. If no override exists, the UI will fallback to the workspace - * default warehouse. + * can fetch overrides for any user. If the user has no override, the request fails with + * `NOT_FOUND` and the workspace default warehouse is used. */ public DefaultWarehouseOverride getDefaultWarehouseOverride( GetDefaultWarehouseOverrideRequest request) { @@ -285,7 +286,8 @@ public Wait stop(StopRequest request) { /** * Updates an existing default warehouse override for a user. Users can update their own override. - * Admins can update overrides for any user. + * Admins can update overrides for any user. If the user has no override, the request fails with + * `NOT_FOUND` unless `allow_missing` is true. */ public DefaultWarehouseOverride updateDefaultWarehouseOverride( UpdateDefaultWarehouseOverrideRequest request) { diff --git a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sql/WarehousesService.java b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sql/WarehousesService.java index ba32296ba..5e4b98881 100644 --- a/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sql/WarehousesService.java +++ b/databricks-sdk-java/src/main/java/com/databricks/sdk/service/sql/WarehousesService.java @@ -19,7 +19,8 @@ public interface WarehousesService { /** * Creates a new default warehouse override for a user. Users can create their own override. - * Admins can create overrides for any user. + * Admins can create overrides for any user. If the user already has an override, the request + * fails with `ALREADY_EXISTS`. */ DefaultWarehouseOverride createDefaultWarehouseOverride( CreateDefaultWarehouseOverrideRequest createDefaultWarehouseOverrideRequest); @@ -43,8 +44,8 @@ void deleteDefaultWarehouseOverride( /** * Returns the default warehouse override for a user. Users can fetch their own override. Admins - * can fetch overrides for any user. If no override exists, the UI will fallback to the workspace - * default warehouse. + * can fetch overrides for any user. If the user has no override, the request fails with + * `NOT_FOUND` and the workspace default warehouse is used. */ DefaultWarehouseOverride getDefaultWarehouseOverride( GetDefaultWarehouseOverrideRequest getDefaultWarehouseOverrideRequest); @@ -91,7 +92,8 @@ void setWorkspaceWarehouseConfig( /** * Updates an existing default warehouse override for a user. Users can update their own override. - * Admins can update overrides for any user. + * Admins can update overrides for any user. If the user has no override, the request fails with + * `NOT_FOUND` unless `allow_missing` is true. */ DefaultWarehouseOverride updateDefaultWarehouseOverride( UpdateDefaultWarehouseOverrideRequest updateDefaultWarehouseOverrideRequest); diff --git a/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtClientHarness.java b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtClientHarness.java new file mode 100644 index 000000000..56949a3fe --- /dev/null +++ b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtClientHarness.java @@ -0,0 +1,149 @@ +package com.databricks.sdk.mixin; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import com.databricks.sdk.core.ApiClient; +import com.databricks.sdk.core.DatabricksConfig; +import com.databricks.sdk.core.DummyCredentialsProvider; +import com.databricks.sdk.core.http.HttpClient; +import com.databricks.sdk.core.http.Request; +import com.databricks.sdk.core.http.Response; +import com.databricks.sdk.core.utils.FakeTimer; +import com.databricks.sdk.mixin.FilesExtEndpoint.Kind; +import com.databricks.sdk.mixin.FilesExtEndpointClients.Transfer; +import com.databricks.sdk.mixin.FilesExtEndpointClients.WorkspaceFilesClient; +import com.databricks.sdk.mixin.FilesExtUploadWalk.UploadClient; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.function.Function; + +/** + * The endpoint clients' tests' rig: a FilesExt built from a config whose HTTP client is the {@link + * FilesExtFakeServer}, optionally wrapped, and the transfer its clients share, on a fake timer. The + * fake checks every request's shape (credentials, session tokens, Content-Length) as the contract + * does. + */ +final class FilesExtClientHarness { + static final String HOST = "http://localhost"; + static final String PATH = "/Volumes/catalog/schema/volume/file.bin"; + + final FilesExtFakeServer.Config cfg = new FilesExtFakeServer.Config(); + final FilesExtFakeServer fake = new FilesExtFakeServer(cfg); + final FakeTimer timer = new FakeTimer(); + final Transfer transfer; + + FilesExtClientHarness() { + this(fake -> fake); + } + + FilesExtClientHarness(Function wrap) { + this(wrap, null); + } + + FilesExtClientHarness(Function wrap, String workspaceIdOrNull) { + HttpClient http = wrap.apply(fake); + DatabricksConfig config = + new DatabricksConfig() + .setHost(HOST) + .setCredentialsProvider(new DummyCredentialsProvider()) + .setHttpClient(http); + FilesExt files = new FilesExt(new ApiClient(config), config); + transfer = + new Transfer( + files.singleAttemptApiClient(), + files.workspaceResponses(), + http, + HOST, + workspaceIdOrNull, + timer, + Clock.fixed(Instant.parse("2026-11-12T00:00:00Z"), ZoneOffset.UTC), + Duration.ofMinutes(5)); + } + + WorkspaceFilesClient workspace() { + return new WorkspaceFilesClient(transfer, new FilesExtEndpoint(Kind.FILES_API_V2, HOST, false)); + } + + FilesExtPresigned.PresignedClient presigned() { + return new FilesExtPresigned.PresignedClient( + transfer, new FilesExtEndpoint(Kind.IO_OFFLOAD, HOST, true)); + } + + /** The built-in order: presigned, then the workspace. */ + List builtInOrder() { + return Arrays.asList(presigned(), workspace()); + } + + /** Uploads {@code content} as a one-pass stream over {@code clients}, with 4-byte parts. */ + static void upload( + List clients, byte[] content, boolean parallel, int minMultipartSize) + throws IOException { + FilesExtUploadWalk.upload( + clients, + FilesExtUploadData.fromStream(new ByteArrayInputStream(content)), + PATH, + null, + 4, + 1, + parallel, + parallel ? 2 : null, + minMultipartSize); + } + + void assertNoViolations() { + assertEquals(Collections.emptyList(), fake.violations()); + assertNull(fake.credentialViolation()); + } + + static Response response(Request request, int status, String body, Map headers) { + Map> all = new HashMap<>(); + headers.forEach((k, v) -> all.put(k, Collections.singletonList(v))); + return new Response(request, status, "status " + status, all, body); + } + + static HttpClient recordingWorkspacePuts(HttpClient fake, List puts) { + return request -> { + if (request.getMethod().equals("PUT") && request.getUri().getHost().equals("localhost")) { + puts.add(request); + } + return fake.execute(request); + }; + } + + /** The transfer threads still alive, each given a moment to finish exiting. */ + static List transferThreads() throws InterruptedException { + List names = new ArrayList<>(); + for (Thread t : Thread.getAllStackTraces().keySet()) { + if (t.getName().startsWith(FilesExtUploadWalk.TRANSFER_THREAD_NAME)) { + t.join(5000); + if (t.isAlive()) { + names.add(t.getName()); + } + } + } + return names; + } + + static void awaitUninterruptibly(CountDownLatch latch) { + while (true) { + try { + latch.await(); + return; + } catch (InterruptedException e) { + // Keep waiting, as a blocked socket read does. + } + } + } +} diff --git a/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtContractTest.java b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtContractTest.java new file mode 100644 index 000000000..b38c68d0e --- /dev/null +++ b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtContractTest.java @@ -0,0 +1,543 @@ +package com.databricks.sdk.mixin; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +import com.databricks.sdk.WorkspaceClient; +import com.databricks.sdk.core.DatabricksConfig; +import com.databricks.sdk.core.DatabricksError; +import com.databricks.sdk.core.DatabricksException; +import com.databricks.sdk.core.DummyCredentialsProvider; +import com.databricks.sdk.core.error.platform.AlreadyExists; +import com.databricks.sdk.core.error.platform.InternalError; +import com.databricks.sdk.core.error.platform.PermissionDenied; +import com.databricks.sdk.core.error.platform.ResourceAlreadyExists; +import com.databricks.sdk.service.files.DownloadRequest; +import com.databricks.sdk.service.files.DownloadResponse; +import com.databricks.sdk.service.files.UploadRequest; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Set; +import java.util.TreeMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.stream.Stream; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestFactory; +import org.junit.jupiter.api.io.TempDir; + +/** + * Checks this SDK's Files transfers against a recorded transfer contract. + * + *

The contract is a matrix of transfer scenarios, each recorded with its expected outcome and + * the requests it makes. This test runs every scenario against {@code workspaceClient.files()} + * through {@link FilesExtFakeServer}. The recording is not distributed with this module; outside + * Bazel the test skips without it. + * + *

The ratchet: a scenario on neither list must match the contract, a scenario in {@code + * known_gaps.txt} must not (remove it once it does), and a scenario in {@code deviations.txt} must + * have its recorded outcome instead of the contract's. Some failures are never a gap and fail even + * for a listed scenario: see {@link Result#unexcused}. + */ +public class FilesExtContractTest { + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String HEADER_FILE = "transfer_contract.json"; + private static final List SCENARIO_FILES = + Arrays.asList("transfer_contract_upload.jsonl", "transfer_contract_download.jsonl"); + private static final String KNOWN_GAPS_FILE = "known_gaps.txt"; + private static final String DEVIATIONS_FILE = "deviations.txt"; + + private static final Duration SCENARIO_TIMEOUT = Duration.ofSeconds(30); + private static final String SCENARIO_THREAD_NAME = "port-contract-scenario"; + + @TempDir Path tempDir; + + /** How one scenario differs from the contract. */ + private static final class Result { + /** Differences a listed gap excuses. */ + final List mismatches = new ArrayList<>(); + + /** + * Failures no gap excuses: workspace credentials on a presigned URL, a hang, a success with the + * wrong bytes, a malformed request on a contract operation (a protocol violation the fake + * records), and probe or scim requests. + */ + final List unexcused = new ArrayList<>(); + + boolean matches() { + return mismatches.isEmpty() && unexcused.isEmpty(); + } + } + + @TestFactory + Stream transferContract() throws IOException { + Contract contract = Contract.load(); + Map> gaps = loadList(KNOWN_GAPS_FILE, 1); + Map> deviations = loadList(DEVIATIONS_FILE, 3); + List tests = new ArrayList<>(); + for (Map scenario : contract.scenarios) { + String id = (String) scenario.get("id"); + List deviation = deviations.get(id); + String want = deviation != null ? deviation.get(0) : expectedOutcome(scenario); + boolean gap = gaps.containsKey(id); + tests.add( + DynamicTest.dynamicTest( + id, + () -> { + Result result = runScenario(contract, scenario, want); + if (!result.unexcused.isEmpty()) { + fail( + "breaks a rule no known gap excuses:\n" + + String.join("\n", result.unexcused)); + } + if (gap && result.matches()) { + fail("passes now: remove it from " + KNOWN_GAPS_FILE); + } + if (!gap && !result.matches()) { + fail("does not match the contract:\n" + String.join("\n", result.mismatches)); + } + })); + } + return tests.stream(); + } + + @Test + void spentBudgets_mapToTheirOutcomes() { + FilesExtRetry.Budget capped = new FilesExtRetry.Budget(3, Duration.ofMinutes(5)); + DatabricksError last = new DatabricksError("TEMPORARILY_UNAVAILABLE", "no", 503); + + assertEquals( + "RETRY_ATTEMPTS_EXHAUSTED", outcome(FilesExtRetry.exhaustedError(capped, 4, last))); + assertEquals("RETRY_TIMEOUT", outcome(FilesExtRetry.exhaustedError(capped, 2, last))); + // Without the last failure, or as a subclass, it is not a spent budget. + assertEquals("UNCLASSIFIED", outcome(FilesExtRetry.exhaustedError(capped, 4, null))); + assertEquals("UNCLASSIFIED", outcome(new DatabricksError("X", "Timed out after PT5M", 500))); + } + + @Test + void listedScenarios_areContractScenarios() throws IOException { + Set ids = Contract.load().ids(); + List unknown = new ArrayList<>(); + for (String file : Arrays.asList(KNOWN_GAPS_FILE, DEVIATIONS_FILE)) { + for (String id : loadList(file, file.equals(KNOWN_GAPS_FILE) ? 1 : 3).keySet()) { + if (!ids.contains(id)) { + unknown.add(file + ": " + id); + } + } + } + if (!unknown.isEmpty()) { + fail("listed but not contract scenarios; remove them:\n" + String.join("\n", unknown)); + } + } + + /** Runs one scenario and returns how the result differs from the contract. */ + private Result runScenario(Contract contract, Map scenario, String wantOutcome) + throws IOException { + Result result = new Result(); + Map k = contract.constants; + String filePath = (String) k.get("file_path"); + String transfer = (String) scenario.get("transfer"); + byte[] data = payload((int) number(contract.sizes.get(scenario.get("size")))); + Map endpointList = (Map) contract.endpointLists.get(scenario.get("endpoint_list")); + Map faults = (Map) scenario.get("faults"); + + FilesExtFakeServer.Config cfg = new FilesExtFakeServer.Config(); + cfg.workspaceHost = (String) k.get("workspace_host"); + cfg.storageProxyHost = (String) k.get("storage_proxy_host"); + cfg.rigHost = (String) k.get("rig_host"); + cfg.cloudHost = (String) k.get("cloud_host"); + cfg.filePath = filePath; + cfg.lastModified = (String) k.get("last_modified"); + Object endpointsApi = endpointList.get("endpoints_api"); + cfg.endpoints = endpointsApi == null ? null : new ArrayList<>((List) endpointsApi); + cfg.faults = decodeFaults(faults, (List) k.get("fault_calls")); + if (transfer.equals("download")) { + cfg.downloadContent = data; + } + FilesExtFakeServer fake = new FilesExtFakeServer(cfg); + // The generated client's retries back off for seconds, which would turn every retryable fault + // into a hang; the transfer extension has its own retry budgets. + WorkspaceClient client = + new WorkspaceClient( + new DatabricksConfig() + .setHost("http://" + cfg.workspaceHost) + .setCredentialsProvider(new DummyCredentialsProvider()) + .setHttpClient(fake) + .setDisableRetries(true)); + + byte[][] downloaded = new byte[1][]; + // The scenario runs on its own daemon thread so that a hang is reported, not waited for. + FutureTask run = + new FutureTask<>( + () -> { + try { + if (transfer.equals("upload")) { + upload(client, filePath, (String) scenario.get("source"), data); + } else { + downloaded[0] = download(client, filePath); + } + return null; + } catch (RuntimeException | IOException | Error e) { + return e; + } + }); + Thread thread = new Thread(run, SCENARIO_THREAD_NAME); + thread.setDaemon(true); + thread.start(); + Throwable error; + try { + error = run.get(SCENARIO_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + } catch (TimeoutException e) { + run.cancel(true); + result.unexcused.add("the scenario did not finish within " + SCENARIO_TIMEOUT); + return result; + } catch (ExecutionException e) { + throw new AssertionError(e.getCause()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError(e); + } + + Map expect = (Map) scenario.get("expect"); + String outcome = outcome(error); + if (!outcome.equals(wantOutcome)) { + result.mismatches.add("outcome = " + outcome + " (" + error + "), want " + wantOutcome); + } + List endpointsUsed = (List) expect.get("endpoints_used"); + if (!fake.endpointsTouched().equals(endpointsUsed)) { + result.mismatches.add( + "endpoints used = " + fake.endpointsTouched() + ", want " + endpointsUsed); + } + Map counts = fake.counts(); + Object requests = expect.get("requests"); + if (requests != null) { + Map want = new TreeMap<>(); + for (Map.Entry e : ((Map) requests).entrySet()) { + want.put((String) e.getKey(), (int) number(e.getValue())); + } + if (!counts.equals(want)) { + result.mismatches.add("requests = " + counts + ", want " + want); + } + } + Object requestOps = expect.get("request_ops"); + if (requestOps != null && !new ArrayList<>(counts.keySet()).equals(requestOps)) { + result.mismatches.add("operations = " + counts.keySet() + ", want " + requestOps); + } + if (transfer.equals("upload")) { + byte[] stored; + try { + stored = fake.storedFile(); + } catch (AssertionError e) { + result.mismatches.add(e.getMessage()); + stored = null; + } + if (outcome.equals("OK") && (stored == null || !Arrays.equals(stored, data))) { + result.unexcused.add( + "the upload succeeded but stored " + + (stored == null ? "nothing" : stored.length + " other bytes") + + ", not the " + + data.length + + " uploaded"); + } + if (!wantOutcome.equals("OK") && stored != null) { + result.mismatches.add("a file was stored by an upload the contract says fails"); + } + } else if (outcome.equals("OK") && !Arrays.equals(downloaded[0], data)) { + result.unexcused.add( + "the download succeeded but read " + + (downloaded[0] == null ? "nothing" : downloaded[0].length + " other bytes") + + ", not the " + + data.length + + " stored"); + } + String credentials = fake.credentialViolation(); + if (credentials != null) { + if (credentials.contains("presigned")) { + result.unexcused.add(credentials); + } else { + result.mismatches.add(credentials); + } + } + if (!fake.violations().isEmpty()) { + result.unexcused.add("protocol violations: " + String.join("; ", fake.violations())); + } + if (counts.containsKey("probe") || counts.containsKey("scim")) { + result.unexcused.add("probe or scim requests were sent"); + } + return result; + } + + /** Uploads through the generated client, the only upload this SDK has: one single-shot PUT. */ + private void upload(WorkspaceClient client, String filePath, String source, byte[] data) + throws IOException { + InputStream contents; + switch (source) { + case "file": + Path local = tempDir.resolve("source.bin"); + Files.write(local, data); + contents = Files.newInputStream(local); + break; + case "seekable": + case "non-seekable": + contents = new ByteArrayInputStream(data); + break; + default: + throw new AssertionError("unknown source " + source); + } + try (InputStream in = contents) { + client.files().upload(new UploadRequest().setFilePath(filePath).setContents(in)); + } + } + + /** Downloads through the generated client, the only download this SDK has. */ + private static byte[] download(WorkspaceClient client, String filePath) throws IOException { + DownloadResponse response = + client.files().download(new DownloadRequest().setFilePath(filePath)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (InputStream in = response.getContents()) { + byte[] buf = new byte[8192]; + for (int n; (n = in.read(buf)) >= 0; ) { + out.write(buf, 0, n); + } + } + return out.toByteArray(); + } + + /** + * Maps a failure to the contract's language-neutral outcome codes. A spent retry budget is a + * {@link DatabricksException} with the extension's message and the last failure as its cause, + * checked first as that cause would otherwise give its own code. A failure with no code of its + * own is UNCLASSIFIED. + */ + private static String outcome(Throwable error) { + if (error == null) { + return "OK"; + } + if (isSpentBudget(error, "Exceeded max retry attempts (")) { + return "RETRY_ATTEMPTS_EXHAUSTED"; + } + if (isSpentBudget(error, "Timed out after ")) { + return "RETRY_TIMEOUT"; + } + if (hasCause(error, AlreadyExists.class) || hasCause(error, ResourceAlreadyExists.class)) { + return "ALREADY_EXISTS"; + } + if (hasCause(error, PermissionDenied.class)) { + return "PERMISSION_DENIED"; + } + if (hasCause(error, InternalError.class)) { + return "INTERNAL"; + } + if (hasCause(error, FilesExtFakeServer.FakeBrokenTransferException.class)) { + return "TRANSFER_BROKEN"; + } + if (hasCause(error, FilesExtFakeServer.FakeNetworkException.class)) { + return "CONNECTION_FAILED"; + } + return "UNCLASSIFIED"; + } + + private static boolean isSpentBudget(Throwable error, String messagePrefix) { + return error.getClass() == DatabricksException.class + && error.getMessage() != null + && error.getMessage().startsWith(messagePrefix) + && error.getCause() != null; + } + + private static boolean hasCause(Throwable error, Class type) { + for (Throwable t = error; t != null; t = t.getCause()) { + if (type.isInstance(t)) { + return true; + } + } + return false; + } + + private static String expectedOutcome(Map scenario) { + return (String) ((Map) scenario.get("expect")).get("outcome"); + } + + /** Returns {@code size} bytes that are the same on every run. */ + private static byte[] payload(int size) { + byte[] data = new byte[size]; + new Random(0x66696c6573L).nextBytes(data); + return data; + } + + /** + * Turns the contract's faults into fake faults. A fault is either one fault for every call, or + * one per call in {@code calls}, the last standing for every later call. + */ + private static Map decodeFaults( + Map raw, List calls) { + Map faults = new HashMap<>(); + for (Map.Entry e : raw.entrySet()) { + List decoded = new ArrayList<>(); + if (e.getValue() instanceof List) { + for (Object f : (List) e.getValue()) { + decoded.add(decodeFault(f)); + } + } else { + decoded.add(decodeFault(e.getValue())); + } + faults.put( + (String) e.getKey(), + call -> { + if (decoded.size() == 1) { + return decoded.get(0); + } + int i = 0; + while (i < calls.size() && number(calls.get(i)) < call) { + i++; + } + return decoded.get(Math.min(i, decoded.size() - 1)); + }); + } + return faults; + } + + private static FilesExtFakeServer.Fault decodeFault(Object raw) { + if (raw == null) { + return null; + } + Map f = (Map) raw; + if (f.get("status") != null) { + return FilesExtFakeServer.Fault.status((int) number(f.get("status"))); + } + if ("connection".equals(f.get("error"))) { + return FilesExtFakeServer.Fault.connection(); + } + if (f.get("break_after") != null) { + return FilesExtFakeServer.Fault.breakAfter(number(f.get("break_after"))); + } + throw new AssertionError("unknown fault " + f); + } + + private static long number(Object value) { + if (!(value instanceof Number)) { + throw new AssertionError("expected a number, got " + value); + } + return ((Number) value).longValue(); + } + + /** The parsed transfer contract: its header and every scenario, in file order. */ + private static final class Contract { + final Map constants; + final Map sizes; + final Map endpointLists; + final List> scenarios; + + private Contract(Map header, List> scenarios) { + this.constants = (Map) header.get("constants"); + this.sizes = (Map) header.get("sizes"); + this.endpointLists = (Map) header.get("endpoint_lists"); + this.scenarios = scenarios; + } + + static Contract load() throws IOException { + byte[] raw = resource(HEADER_FILE); + // The contract is not published with the SDK, so the public build skips; under Bazel (which + // sets TEST_SRCDIR) it is a test resource, and a missing one is an error. + if (raw == null && System.getenv("TEST_SRCDIR") != null) { + throw new AssertionError("the transfer contract is missing from the test resources"); + } + Assumptions.assumeTrue(raw != null, "the transfer contract is not available"); + Map header = MAPPER.readValue(raw, Map.class); + if (number(header.get("version")) != 1) { + throw new AssertionError(HEADER_FILE + ": version " + header.get("version") + ", want 1"); + } + List> scenarios = new ArrayList<>(); + for (String file : SCENARIO_FILES) { + byte[] lines = resource(file); + if (lines == null) { + throw new AssertionError("missing " + file); + } + int n = 0; + for (String line : new String(lines, UTF_8).split("\n", -1)) { + n++; + if (line.isEmpty()) { + continue; + } + try { + scenarios.add(MAPPER.readValue(line, Map.class)); + } catch (IOException e) { + throw new AssertionError(file + ":" + n + ": " + e.getMessage(), e); + } + } + } + return new Contract(header, scenarios); + } + + /** The scenario IDs, which must be unique: the ratchet lists are keyed by them. */ + Set ids() { + Set ids = new HashSet<>(); + for (Map s : scenarios) { + if (!ids.add((String) s.get("id"))) { + throw new AssertionError("scenario \"" + s.get("id") + "\" is in the contract twice"); + } + } + return ids; + } + } + + /** + * Reads a tab-separated list keyed by scenario ID. Blank lines and lines starting with # are + * ignored. + */ + private static Map> loadList(String file, int fields) throws IOException { + byte[] raw = resource(file); + if (raw == null) { + throw new AssertionError("missing " + file); + } + Map> list = new LinkedHashMap<>(); + String[] lines = new String(raw, UTF_8).split("\n", -1); + for (int i = 0; i < lines.length; i++) { + String line = lines[i]; + if (line.isEmpty() || line.startsWith("#")) { + continue; + } + String[] parts = line.split("\t", -1); + if (parts.length != fields) { + throw new AssertionError( + file + ":" + (i + 1) + ": " + parts.length + " tab-separated fields, want " + fields); + } + if (list.put(parts[0], Arrays.asList(parts).subList(1, parts.length)) != null) { + throw new AssertionError(file + ":" + (i + 1) + ": \"" + parts[0] + "\" is listed twice"); + } + } + return list; + } + + private static byte[] resource(String name) throws IOException { + try (InputStream in = FilesExtContractTest.class.getResourceAsStream("filesext/" + name)) { + if (in == null) { + return null; + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buf = new byte[65536]; + for (int n; (n = in.read(buf)) >= 0; ) { + out.write(buf, 0, n); + } + return out.toByteArray(); + } + } +} diff --git a/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtEndpointClientsTest.java b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtEndpointClientsTest.java new file mode 100644 index 000000000..968f4635c --- /dev/null +++ b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtEndpointClientsTest.java @@ -0,0 +1,345 @@ +package com.databricks.sdk.mixin; + +import static com.databricks.sdk.mixin.FilesExtClientHarness.HOST; +import static com.databricks.sdk.mixin.FilesExtClientHarness.PATH; +import static com.databricks.sdk.mixin.FilesExtClientHarness.recordingWorkspacePuts; +import static com.databricks.sdk.mixin.FilesExtClientHarness.response; +import static com.databricks.sdk.mixin.FilesExtClientHarness.upload; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.databricks.sdk.core.ApiClient; +import com.databricks.sdk.core.DatabricksConfig; +import com.databricks.sdk.core.DatabricksError; +import com.databricks.sdk.core.DummyCredentialsProvider; +import com.databricks.sdk.core.commons.CommonsHttpClient; +import com.databricks.sdk.core.error.platform.PermissionDenied; +import com.databricks.sdk.core.http.HttpClient; +import com.databricks.sdk.core.http.Request; +import com.databricks.sdk.core.utils.FakeTimer; +import com.databricks.sdk.mixin.FilesExtEndpoint.Kind; +import com.databricks.sdk.mixin.FilesExtEndpointClients.Transfer; +import com.databricks.sdk.mixin.FilesExtEndpointClients.WorkspaceFilesClient; +import com.sun.net.httpserver.HttpServer; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * The workspace Files API 2.0 client and the helpers every endpoint client shares, against the + * {@link FilesExtFakeServer}. + */ +public class FilesExtEndpointClientsTest { + @TempDir Path tempDir; + + private static final byte[] TEN = "0123456789".getBytes(UTF_8); + + @Test + void workspace_smallDataGoesInOneShotWithItsLength() throws IOException { + List puts = new ArrayList<>(); + FilesExtClientHarness h = new FilesExtClientHarness(fake -> recordingWorkspacePuts(fake, puts)); + + upload(Collections.singletonList(h.workspace()), Arrays.copyOf(TEN, 3), false, 10); + + assertArrayEquals(Arrays.copyOf(TEN, 3), h.fake.storedFile()); + assertEquals(1, puts.size()); + assertEquals("3", puts.get(0).getHeaders().get("Content-Length")); + assertEquals(Collections.singletonList("floor"), h.fake.endpointsTouched()); + h.assertNoViolations(); + } + + @Test + void workspace_emptyDataGoesInOneShotAsAnEmptyStringBody() throws IOException { + List puts = new ArrayList<>(); + FilesExtClientHarness h = new FilesExtClientHarness(fake -> recordingWorkspacePuts(fake, puts)); + + upload(Collections.singletonList(h.workspace()), new byte[0], false, 10); + + assertArrayEquals(new byte[0], h.fake.storedFile()); + // A string body is sent with Content-Length: 0; an empty stream would go chunked. + assertEquals(1, puts.size()); + assertFalse(puts.get(0).isBodyStreaming()); + assertEquals(Integer.valueOf(1), h.fake.counts().get("floor.single")); + h.assertNoViolations(); + } + + @Test + void workspaceSingleShot_preconditionFailed_raisesWithoutRetrying() { + FilesExtClientHarness h = new FilesExtClientHarness(); + h.cfg.faults.put( + "floor.single", FilesExtFakeServer.always(FilesExtFakeServer.Fault.status(412))); + + // A second endpoint, which a walk would move to: a raise never reaches it. + FilesExtClientHarness next = new FilesExtClientHarness(); + + assertThrows( + DatabricksError.class, + () -> + upload( + Arrays.asList(h.workspace(), next.workspace()), Arrays.copyOf(TEN, 3), false, 10)); + + assertEquals(Integer.valueOf(1), h.fake.counts().get("floor.single")); + assertTrue(next.fake.counts().isEmpty(), next.fake.counts().toString()); + } + + @Test + void requests_carryOverwriteAndTheWorkspaceId() throws IOException { + List sent = new ArrayList<>(); + FilesExtClientHarness h = + new FilesExtClientHarness( + fake -> + request -> { + sent.add(request); + return fake.execute(request); + }, + "123"); + + FilesExtUploadWalk.upload( + Collections.singletonList(h.workspace()), + FilesExtUploadData.fromStream(new ByteArrayInputStream(Arrays.copyOf(TEN, 3))), + PATH, + false, + 4, + 1, + false, + null, + 10); + + Request put = + sent.stream() + .filter(r -> r.getMethod().equals("PUT")) + .findFirst() + .orElseThrow(AssertionError::new); + assertEquals("false", FilesExtFakeServer.query(put.getUri()).get("overwrite")); + assertEquals("123", put.getHeaders().get("X-Databricks-Workspace-Id")); + } + + @ParameterizedTest(name = "{0}") + @ValueSource(strings = {"single shot", "control call"}) + void aRequestWithAQuery_keepsTheEscapesOfItsPath(String kind) throws Exception { + String path = "/Volumes/catalog/schema/volume/a b#c%d\u00e9.bin"; + List sent = new ArrayList<>(); + FilesExtClientHarness h = + new FilesExtClientHarness( + fake -> + request -> { + if (!request.getMethod().equals("GET")) { + sent.add(request); + } + return response(request, 200, "{}", Collections.emptyMap()); + }); + + String query; + if (kind.equals("single shot")) { + FilesExtUploadWalk.upload( + Collections.singletonList(h.workspace()), + FilesExtUploadData.fromStream(new ByteArrayInputStream(Arrays.copyOf(TEN, 3))), + path, + true, + 4, + 1, + false, + null, + 10); + query = "overwrite=true"; + } else { + h.transfer.postJson( + FilesExtEndpointClients.filesApiPath(path), + FilesExtEndpointClients.query("action", "initiate-upload", "a b", "c&d"), + null); + // In name order, form-encoded, as the SDK encodes query params. + query = "a+b=c%26d&action=initiate-upload"; + } + + assertEquals(1, sent.size()); + assertEquals( + HOST + "/api/2.0/fs/files/Volumes/catalog/schema/volume/a%20b%23c%25d%C3%A9.bin?" + query, + sent.get(0).getUri().toString()); + } + + @Test + void urlExpireTime_isAnHourAheadInRfc3339() { + assertEquals("2026-11-12T01:00:00Z", new FilesExtClientHarness().transfer.urlExpireTime()); + } + + @Test + void responseError_keepsADatabricksErrorOrTypesTheMessageByStatus() { + Request request = new Request("PUT", "https://cloud.example.com/part/1"); + + DatabricksError xml = + FilesExtEndpointClients.responseError( + response(request, 403, "", Collections.emptyMap()), + "Unsuccessful chunk upload"); + DatabricksError json = + FilesExtEndpointClients.responseError( + response( + request, + 403, + "{\"error_code\":\"PERMISSION_DENIED\",\"message\":\"no access\"}", + Collections.emptyMap()), + "ignored"); + + assertTrue(xml instanceof PermissionDenied, xml.toString()); + assertEquals("Unsuccessful chunk upload", xml.getMessage()); + assertEquals("no access", json.getMessage()); + } + + @Test + void filesApiPath_escapesAndCollapsesADoubledSlash() { + assertEquals( + "/api/2.0/fs/files/Volumes/a%20b/c", + FilesExtEndpointClients.filesApiPath("/Volumes/a b/c")); + assertEquals( + "/api/2.0/fs/files/Volumes/c", FilesExtEndpointClients.filesApiPath("//Volumes/c")); + } + + @Test + void workspaceSingleShot_waitsTheServersRetryAfter() throws IOException { + AtomicBoolean throttled = new AtomicBoolean(); + FilesExtClientHarness h = + new FilesExtClientHarness( + fake -> + request -> { + if (request.getMethod().equals("PUT") && throttled.compareAndSet(false, true)) { + request.getBodyString(); + return response( + request, + 429, + "{\"error_code\":\"TOO_MANY_REQUESTS\",\"message\":\"slow down\"}", + Collections.singletonMap("Retry-After", "7")); + } + return fake.execute(request); + }); + + upload(Collections.singletonList(h.workspace()), Arrays.copyOf(TEN, 3), false, 10); + + assertArrayEquals(Arrays.copyOf(TEN, 3), h.fake.storedFile()); + long waited = h.timer.getCurrentTime(); + assertTrue(waited >= 7000 && waited < 8000, waited + " ms"); + } + + @Test + void postJson_withoutABody_sendsAnEmptyBodyWithItsLength() throws Exception { + List seen = new CopyOnWriteArrayList<>(); + HttpServer server = + HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + server.createContext( + "/", + exchange -> { + seen.add( + "Content-Length=" + + exchange.getRequestHeaders().getFirst("Content-Length") + + " Transfer-Encoding=" + + exchange.getRequestHeaders().getFirst("Transfer-Encoding") + + " query=" + + exchange.getRequestURI().getRawQuery()); + byte[] answer = "{}".getBytes(UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, answer.length); + exchange.getResponseBody().write(answer); + exchange.close(); + }); + server.start(); + try { + String host = "http://127.0.0.1:" + server.getAddress().getPort(); + CommonsHttpClient commons = new CommonsHttpClient.Builder().withTimeoutSeconds(5).build(); + List sent = new ArrayList<>(); + HttpClient recording = + request -> { + if (!request.getMethod().equals("GET")) { + sent.add(request); + } + return commons.execute(request); + }; + DatabricksConfig config = + new DatabricksConfig() + .setHost(host) + .setConfigFile(tempDir.resolve("no-databrickscfg").toString()) + .setCredentialsProvider(new DummyCredentialsProvider()) + .setHttpClient(recording); + FilesExt files = new FilesExt(new ApiClient(config), config); + Transfer transfer = + new Transfer( + files.singleAttemptApiClient(), + files.workspaceResponses(), + recording, + host, + null, + new FakeTimer(), + Clock.systemUTC(), + Duration.ofMinutes(1)); + + transfer.postJson( + FilesExtEndpointClients.filesApiPath(PATH), + FilesExtEndpointClients.query( + "action", "abort-upload", "upload_type", "multipart", "session_token", "secret"), + null); + + // A string body, so the HTTP client never takes the path that logs a request without one. + assertEquals(1, sent.size()); + assertTrue(sent.get(0).isBodyString()); + assertEquals("", sent.get(0).getBodyString()); + assertEquals( + Collections.singletonList( + "Content-Length=0 Transfer-Encoding=null" + + " query=action=abort-upload&session_token=secret&upload_type=multipart"), + seen.subList(seen.size() - 1, seen.size())); + } finally { + server.stop(0); + } + } + + @Test + void postJson_aMalformedAnswerIsAnUnexpectedResponse() { + FilesExtClientHarness h = + new FilesExtClientHarness( + fake -> + request -> response(request, 200, "proxy", Collections.emptyMap())); + + IllegalArgumentException e = + assertThrows( + IllegalArgumentException.class, + () -> + h.transfer.postJson( + "/api/2.0/fs/files/x", + Collections.singletonMap("action", "initiate-upload"), + null)); + + // An answer that isn't JSON walks: it is not a dropped connection. + assertTrue(e.getMessage().startsWith("Unexpected server response"), e.getMessage()); + assertEquals(FilesExtRetry.Decision.WALK, FilesExtRetry.apiClientDecision(e)); + } + + @Test + void workspaceClient_takesOnlyTheWorkspaceHost() { + FilesExtClientHarness h = new FilesExtClientHarness(); + FilesExtEndpoint other = + new FilesExtEndpoint(Kind.FILES_API_V2, "https://proxy.example.com", true); + + assertEquals( + FilesExtEndpointClients.origin("HTTP://LOCALHOST:80/x"), + FilesExtEndpointClients.origin(HOST)); + assertFalse( + FilesExtEndpointClients.origin("no-scheme") + .equals(FilesExtEndpointClients.origin("other"))); + assertThrows(IllegalArgumentException.class, () -> new WorkspaceFilesClient(h.transfer, other)); + } +} diff --git a/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtFakeServer.java b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtFakeServer.java new file mode 100644 index 000000000..0c2fa455b --- /dev/null +++ b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtFakeServer.java @@ -0,0 +1,826 @@ +package com.databricks.sdk.mixin; + +import static java.nio.charset.StandardCharsets.UTF_8; + +import com.databricks.sdk.core.http.HttpClient; +import com.databricks.sdk.core.http.Request; +import com.databricks.sdk.core.http.Response; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URLDecoder; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import org.apache.http.ConnectionClosedException; + +/** + * The FilesExt tests' fake server: an in-process fake of the hosts a Files transfer talks to. They + * are the workspace (Files API 2.0, the upload control plane and the endpoints API), the storage + * proxy, a Files API 3.0 host, and a cloud store reached through presigned URLs. It serves the + * operations the transfer contract records, one for one. It is the SDK's {@link HttpClient}: + * requests never reach the network. It is safe for concurrent use. + */ +final class FilesExtFakeServer implements HttpClient { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + /** The failure of a request whose operation has a connection fault. */ + static final class FakeNetworkException extends IOException { + FakeNetworkException(String message) { + super(message); + } + } + + /** + * The failure of a read from a download whose operation has a break fault: the exception Apache + * HttpCore throws when a Content-Length body ends early, as the classic SDK's transport reports + * it. + */ + static final class FakeBrokenTransferException extends ConnectionClosedException { + FakeBrokenTransferException(String message) { + super(message); + } + } + + /** How one call of an operation fails. */ + static final class Fault { + final int status; + final boolean connection; + final long breakAfter; + + private Fault(int status, boolean connection, long breakAfter) { + this.status = status; + this.connection = connection; + this.breakAfter = breakAfter; + } + + /** Answers the call with this HTTP status and a Databricks error body. */ + static Fault status(int status) { + return new Fault(status, false, -1); + } + + /** Fails the call with a {@link FakeNetworkException} before any response. */ + static Fault connection() { + return new Fault(0, true, -1); + } + + /** For a download, cuts the response body after {@code n} bytes. */ + static Fault breakAfter(long n) { + return new Fault(0, false, n); + } + + boolean breaks() { + return breakAfter >= 0; + } + + @Override + public String toString() { + return connection + ? "connection" + : breaks() ? "break after " + breakAfter : "status " + status; + } + } + + /** The fault of the {@code call}-th call of an operation, counting from 1, or null for none. */ + @FunctionalInterface + interface FaultFunction { + Fault fault(int call); + } + + static FaultFunction always(Fault fault) { + return call -> fault; + } + + static FaultFunction onCalls(Fault fault, Integer... calls) { + List listed = Arrays.asList(calls); + return call -> listed.contains(call) ? fault : null; + } + + /** Configures the fake. */ + static final class Config { + /** Serves Files API 2.0, the upload control plane and the endpoints API. */ + String workspaceHost = "localhost"; + + /** Serves Files API 2.0. */ + String storageProxyHost = "proxy.example.com"; + + /** Serves Files API 3.0. */ + String rigHost = "rig.example.com"; + + /** Serves presigned part uploads and downloads. */ + String cloudHost = "cloud.example.com"; + + /** The one remote file the fake stores and serves. */ + String filePath = "/Volumes/catalog/schema/volume/file.bin"; + + /** The Last-Modified header of downloads and metadata. */ + String lastModified = "Thu, 28 Nov 2024 16:39:14 GMT"; + + /** + * The list {@code GET /api/2.0/fs/endpoints} answers with. When null, the workspace does not + * serve that API and answers 404. + */ + List endpoints; + + /** The faults of each operation's calls, by operation name. */ + Map faults = new HashMap<>(); + + /** The content of the file downloads read. */ + byte[] downloadContent = new byte[0]; + } + + /** Operations on presigned cloud URLs. They must never carry workspace credentials. */ + private static final Set PRESIGNED_OPS = + new HashSet<>(Arrays.asList("offload.part", "offload.get")); + + /** Requests that pick the endpoint list or read file metadata rather than transfer data. */ + private static final Set NOT_ENDPOINTS = + new HashSet<>(Arrays.asList("endpoints", "scim", "probe", "workspace")); + + /** Error codes of the error bodies, by HTTP status. */ + private static final Map ERROR_CODES = new HashMap<>(); + + static { + ERROR_CODES.put(400, "INVALID_PARAMETER_VALUE"); + ERROR_CODES.put(403, "PERMISSION_DENIED"); + ERROR_CODES.put(404, "NOT_FOUND"); + ERROR_CODES.put(409, "ALREADY_EXISTS"); + ERROR_CODES.put(500, "INTERNAL_ERROR"); + } + + private final Config cfg; + private final Object lock = new Object(); + private final List calls = new ArrayList<>(); + private final Map counts = new HashMap<>(); + private final Map> parts = new HashMap<>(); + private final Map stored = new HashMap<>(); + private final Set aborted = new HashSet<>(); + private final Map> credentials = new HashMap<>(); + private final Map> ranges = new HashMap<>(); + private final List violations = new ArrayList<>(); + private final List sdkRequests = new ArrayList<>(); + + FilesExtFakeServer(Config cfg) { + this.cfg = cfg; + } + + /** A protocol check that failed: the request is answered 400 and recorded. */ + private static final class ViolationException extends Exception { + ViolationException(String message) { + super(message); + } + } + + /** + * The SDK's own host-metadata request, which is not part of a transfer. It is answered 404, which + * the SDK treats as no metadata, and is not a contract operation. + */ + static final String HOST_METADATA_PATH = "/.well-known/databricks-config"; + + @Override + public Response execute(Request request) throws IOException { + if (request.getUri().getHost().equals(cfg.workspaceHost) + && request.getUri().getPath().equals(HOST_METADATA_PATH)) { + drain(request); + synchronized (lock) { + sdkRequests.add(request.getMethod() + " " + HOST_METADATA_PATH); + } + return jsonResponse(request, 404, Collections.singletonMap("error_code", "NOT_FOUND")); + } + String op; + try { + op = operation(request); + } catch (ViolationException e) { + return violation(request, e); + } + int call; + synchronized (lock) { + calls.add(op); + call = counts.merge(op, 1, Integer::sum); + credentials + .computeIfAbsent(op, k -> new ArrayList<>()) + .add(header(request, "Authorization") != null); + } + FaultFunction faults = cfg.faults.get(op); + Fault fault = faults == null ? null : faults.fault(call); + if (fault != null && fault.connection) { + drain(request); + throw new FakeNetworkException("fake server: simulated network failure on " + op); + } + if (fault != null && fault.status != 0) { + drain(request); + Map error = new LinkedHashMap<>(); + error.put("error_code", ERROR_CODES.getOrDefault(fault.status, "UNKNOWN")); + error.put("message", "simulated " + fault.status + " on " + op); + return jsonResponse(request, fault.status, error); + } + try { + return respond(op, request, fault); + } catch (ViolationException e) { + return violation(request, e); + } + } + + /** + * Records a protocol check that failed and answers 400, so that a client that swallows its + * request errors cannot hide it from the test. + */ + private Response violation(Request request, ViolationException e) throws IOException { + drain(request); + synchronized (lock) { + violations.add(e.getMessage()); + } + return jsonResponse(request, 400, Collections.singletonMap("message", e.getMessage())); + } + + private String operation(Request request) throws ViolationException { + URI uri = request.getUri(); + String host = uri.getHost(); + String method = request.getMethod(); + String path = uri.getPath(); + Map query = query(uri); + if (host.equals(cfg.workspaceHost) + && path.equals("/api/2.0/fs/endpoints") + && method.equals("GET")) { + return "endpoints"; + } + if (host.equals(cfg.workspaceHost) + && path.equals("/api/2.0/preview/scim/v2/Me") + && method.equals("GET")) { + return "scim"; + } + if (host.equals(cfg.storageProxyHost) + && path.equals("/api/2.0/fs/files/DatabricksInternal/Probe/fullstack/wis")) { + return "probe"; + } + if (path.equals("/api/3.0/fs/files" + cfg.filePath)) { + if (!host.equals(cfg.rigHost)) { + throw new ViolationException("files API 3.0 request to " + host); + } + if (query.containsKey("upload_type") || query.containsKey("session_token")) { + throw new ViolationException("2.0 parameters on " + uri); + } + String action = query.getOrDefault("action", ""); + if (method.equals("POST") + && (action.equals("initiate-upload") + || action.equals("complete-upload") + || action.equals("abort-upload"))) { + return "rig." + action.substring(0, action.indexOf('-')); + } + if (method.equals("PUT") && query.containsKey("part_number")) { + return "rig.part"; + } + if (method.equals("PUT")) { + return "rig.single"; + } + if (method.equals("GET")) { + return "rig.get"; + } + } + if (path.equals("/api/2.0/fs/files" + cfg.filePath)) { + if (!host.equals(cfg.workspaceHost) && !host.equals(cfg.storageProxyHost)) { + throw new ViolationException("files API 2.0 request to " + host); + } + // The workspace's control plane is the "offload" endpoint and its single-shot Files API the + // "floor"; the storage proxy is "dp" for both. + boolean proxy = host.equals(cfg.storageProxyHost); + String control = proxy ? "dp" : "offload"; + String transfer = proxy ? "dp" : "floor"; + String action = query.getOrDefault("action", ""); + if (method.equals("POST") && action.equals("initiate-upload")) { + return control + ".initiate"; + } + if (method.equals("POST") && action.equals("complete-upload")) { + return control + ".complete"; + } + if (method.equals("POST") && action.equals("abort-upload")) { + if (!"multipart".equals(query.get("upload_type"))) { + throw new ViolationException("abort-upload without upload_type: " + uri); + } + return control + ".abort"; + } + if (method.equals("PUT") && "multipart".equals(query.get("upload_type"))) { + if (!proxy) { + throw new ViolationException("multipart part sent to the workspace Files API: " + uri); + } + return "dp.part"; + } + if (method.equals("PUT")) { + return transfer + ".single"; + } + if (method.equals("GET")) { + return transfer + ".get"; + } + if (method.equals("HEAD") && host.equals(cfg.workspaceHost)) { + return "workspace.head"; + } + } + if (host.equals(cfg.workspaceHost) && path.equals("/api/2.0/fs/create-upload-part-urls")) { + return "offload.part-urls"; + } + if (host.equals(cfg.workspaceHost) && path.equals("/api/2.0/fs/create-download-url")) { + return "offload.download-url"; + } + if (host.equals(cfg.cloudHost) && path.startsWith("/part/") && method.equals("PUT")) { + return "offload.part"; + } + if (host.equals(cfg.cloudHost) && path.equals("/download") && method.equals("GET")) { + return "offload.get"; + } + throw new ViolationException("unexpected request " + method + " " + uri); + } + + private Response respond(String op, Request request, Fault fault) + throws IOException, ViolationException { + switch (op) { + case "endpoints": + drain(request); + if (cfg.endpoints == null) { + Map error = new LinkedHashMap<>(); + error.put("error_code", "NOT_FOUND"); + error.put("message", "no endpoints API"); + return jsonResponse(request, 404, error); + } + return jsonResponse(request, 200, Collections.singletonMap("endpoints", cfg.endpoints)); + case "scim": + drain(request); + return response( + request, + 200, + headers("Content-Type", "application/json", "X-Databricks-Org-Id", "12345"), + "{}".getBytes(UTF_8)); + case "probe": + drain(request); + return response(request, 200, headers(), new byte[0]); + default: + break; + } + int dot = op.indexOf('.'); + String endpoint = op.substring(0, dot); + String action = op.substring(dot + 1); + Map query = query(request.getUri()); + if (endpoint.equals("rig") + && (action.equals("part") || action.equals("complete") || action.equals("abort")) + && !"upload-rig".equals(query.get("upload_id"))) { + throw new ViolationException(op + " without the upload_id from initiate-upload"); + } + // The session_token from initiate-upload, on every later call that names the upload. A + // presigned part URL carries none: the URL itself names the part. + if (!endpoint.equals("rig") + && (action.equals("complete") + || action.equals("abort") + || (action.equals("part") && !endpoint.equals("offload"))) + && !("token-" + endpoint).equals(query.get("session_token"))) { + throw new ViolationException( + op + " with session_token \"" + query.get("session_token") + "\""); + } + if (endpoint.equals("rig") + && (action.equals("part") || action.equals("single")) + && !sendsContentLength(request)) { + throw new ViolationException("files API 3.0 requires a Content-Length on " + op); + } + if ((op.equals("offload.part") || op.equals("dp.part")) && !sendsContentLength(request)) { + // Cloud storage rejects a chunked part PUT: S3 with 501, and Azure needs a length. + throw new ViolationException("a multipart part PUT requires a Content-Length on " + op); + } + byte[] body = readBody(request); + if (op.equals("rig.initiate")) { + return jsonResponse(request, 200, Collections.singletonMap("upload_id", "upload-rig")); + } + switch (action) { + case "initiate": + return jsonResponse( + request, + 200, + Collections.singletonMap( + "multipart_upload", + Collections.singletonMap("session_token", "token-" + endpoint))); + case "part-urls": + return partUrls(request, body); + case "part": + return part(request, endpoint, body); + case "complete": + return complete(request, endpoint, body); + case "abort": + synchronized (lock) { + aborted.add(endpoint); + } + return jsonResponse(request, 200, Collections.emptyMap()); + case "single": + synchronized (lock) { + stored.put(endpoint, body); + } + return jsonResponse(request, 200, Collections.emptyMap()); + case "download-url": + Map url = new LinkedHashMap<>(); + url.put("url", "https://" + cfg.cloudHost + "/download"); + url.put("headers", Collections.emptyList()); + return jsonResponse(request, 200, url); + case "head": + return response(request, 200, contentHeaders(cfg.downloadContent.length), new byte[0]); + case "get": + return download(request, endpoint, fault); + default: + throw new ViolationException("no response for " + op); + } + } + + private Response partUrls(Request request, byte[] body) throws IOException, ViolationException { + Map in = jsonObject(body, "create-upload-part-urls body"); + if (!"token-offload".equals(in.get("session_token"))) { + throw new ViolationException( + "create-upload-part-urls with session_token \"" + in.get("session_token") + "\""); + } + long start = number(in.get("start_part_number")); + long count = number(in.get("count")); + List urls = new ArrayList<>(); + for (long n = start; n < start + count; n++) { + Map url = new LinkedHashMap<>(); + url.put("part_number", n); + url.put("url", "https://" + cfg.cloudHost + "/part/" + n); + url.put("headers", Collections.emptyList()); + urls.add(url); + } + return jsonResponse(request, 200, Collections.singletonMap("upload_part_urls", urls)); + } + + private Response part(Request request, String endpoint, byte[] body) + throws IOException, ViolationException { + String raw; + if (endpoint.equals("offload")) { + String path = request.getUri().getPath(); + raw = path.substring(path.lastIndexOf('/') + 1); + } else { + raw = query(request.getUri()).getOrDefault("part_number", ""); + } + int number; + try { + number = Integer.parseInt(raw); + } catch (NumberFormatException e) { + throw new ViolationException("part number \"" + raw + "\": " + e.getMessage()); + } + synchronized (lock) { + parts.computeIfAbsent(endpoint, k -> new HashMap<>()).put(number, body); + } + return response(request, 200, headers("ETag", "etag-" + endpoint + "-" + number), new byte[0]); + } + + private Response complete(Request request, String endpoint, byte[] body) + throws IOException, ViolationException { + Map in = jsonObject(body, "complete-upload body"); + Object listed = in.get("parts"); + List numbers = new ArrayList<>(); + if (listed != null && !(listed instanceof List)) { + throw new ViolationException("complete-upload parts " + listed + " is not a JSON list"); + } + if (listed instanceof List) { + for (Object p : (List) listed) { + if (!(p instanceof Map)) { + throw new ViolationException("complete-upload part " + p + " is not a JSON object"); + } + Map part = (Map) p; + int n = (int) number(part.get("part_number")); + String want = "etag-" + endpoint + "-" + n; + if (!want.equals(part.get("etag"))) { + throw new ViolationException( + "complete-upload part " + + n + + " with etag \"" + + part.get("etag") + + "\", want \"" + + want + + "\""); + } + numbers.add(n); + } + } + synchronized (lock) { + Map uploaded = parts.getOrDefault(endpoint, Collections.emptyMap()); + List sorted = new ArrayList<>(new TreeSet<>(uploaded.keySet())); + if (!numbers.equals(sorted)) { + throw new ViolationException( + "complete-upload must list every uploaded part: got " + + numbers + + ", uploaded " + + sorted); + } + ByteArrayOutputStream file = new ByteArrayOutputStream(); + for (byte[] data : new TreeMap<>(uploaded).values()) { + file.write(data, 0, data.length); + } + stored.put(endpoint, file.toByteArray()); + } + return jsonResponse(request, 200, Collections.emptyMap()); + } + + private Response download(Request request, String endpoint, Fault fault) + throws IOException, ViolationException { + String rangeHeader = header(request, "Range"); + synchronized (lock) { + ranges + .computeIfAbsent(endpoint, k -> new ArrayList<>()) + .add(rangeHeader == null ? "" : rangeHeader); + } + byte[] data = cfg.downloadContent; + int status = 200; + if (rangeHeader != null && !rangeHeader.isEmpty()) { + int dash = rangeHeader.indexOf('-'); + if (!rangeHeader.startsWith("bytes=") || dash < 0) { + throw new ViolationException("unsupported Range \"" + rangeHeader + "\""); + } + int start; + int end = data.length - 1; + try { + start = Integer.parseInt(rangeHeader.substring("bytes=".length(), dash)); + String endText = rangeHeader.substring(dash + 1); + if (!endText.isEmpty()) { + end = Integer.parseInt(endText); + } + } catch (NumberFormatException e) { + throw new ViolationException("Range \"" + rangeHeader + "\": " + e.getMessage()); + } + // A range past the end of the file is served empty, as the contract records it. + end = Math.min(end, data.length - 1); + start = Math.min(start, end + 1); + data = Arrays.copyOfRange(data, start, end + 1); + status = 206; + } + InputStream body = + fault != null && fault.breaks() + ? new BreakingInputStream(data, fault.breakAfter) + : new ByteArrayInputStream(data); + return new Response( + request, + request.getUri().toURL(), + status, + "status " + status, + contentHeaders(data.length), + body); + } + + private Map> contentHeaders(long length) { + return headers( + "Content-Length", + Long.toString(length), + "Content-Type", + "application/octet-stream", + "Last-Modified", + cfg.lastModified); + } + + /** Serves the first {@code breakAt} bytes, then fails like a dropped connection. */ + private static final class BreakingInputStream extends InputStream { + private final byte[] data; + private final long breakAt; + private int pos; + + BreakingInputStream(byte[] data, long breakAt) { + this.data = data; + this.breakAt = breakAt; + } + + @Override + public int read() throws IOException { + byte[] one = new byte[1]; + int n = read(one, 0, 1); + return n < 0 ? -1 : one[0] & 0xff; + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + if (pos >= breakAt) { + throw new FakeBrokenTransferException( + "fake server: download broken after " + pos + " bytes"); + } + long end = Math.min(Math.min(breakAt, data.length), (long) pos + len); + if (end <= pos) { + return len == 0 ? 0 : -1; + } + int n = (int) (end - pos); + System.arraycopy(data, pos, b, off, n); + pos += n; + return n; + } + } + + /** Every operation in the order it was received. */ + List calls() { + synchronized (lock) { + return new ArrayList<>(calls); + } + } + + /** How many times each operation was called, sorted by operation. */ + Map counts() { + synchronized (lock) { + return new TreeMap<>(counts); + } + } + + /** + * The endpoints in the order they were first used, ignoring the probe, metadata and endpoint-list + * requests. + */ + List endpointsTouched() { + List seen = new ArrayList<>(); + for (String op : calls()) { + int dot = op.indexOf('.'); + String endpoint = dot < 0 ? op : op.substring(0, dot); + if (!NOT_ENDPOINTS.contains(endpoint) && !seen.contains(endpoint)) { + seen.add(endpoint); + } + } + return seen; + } + + /** + * The file as a caller would read it back, whichever endpoint stored it, or null if none did. + * + * @throws AssertionError if more than one endpoint stored it + */ + byte[] storedFile() { + synchronized (lock) { + if (stored.size() > 1) { + throw new AssertionError( + "the file was stored by more than one endpoint: " + new TreeSet<>(stored.keySet())); + } + return stored.isEmpty() ? null : stored.values().iterator().next(); + } + } + + /** Whether {@code endpoint} received an abort-upload. */ + boolean aborted(String endpoint) { + synchronized (lock) { + return aborted.contains(endpoint); + } + } + + /** The Range headers of the downloads from {@code endpoint}, empty for a whole file. */ + List ranges(String endpoint) { + synchronized (lock) { + return new ArrayList<>(ranges.getOrDefault(endpoint, Collections.emptyList())); + } + } + + /** The SDK's own requests outside the contract, such as {@link #HOST_METADATA_PATH}. */ + List sdkRequests() { + synchronized (lock) { + return new ArrayList<>(sdkRequests); + } + } + + /** The protocol checks that failed. */ + List violations() { + synchronized (lock) { + return new ArrayList<>(violations); + } + } + + /** + * Returns why the credential rules were broken, or null if they were not: workspace credentials + * must never reach a presigned URL, and every request to a Databricks host must carry them. + */ + String credentialViolation() { + synchronized (lock) { + Map> byOp = new TreeMap<>(credentials); + // A leak to a presigned URL first, so that a missing credential elsewhere cannot hide it. + for (Map.Entry> e : byOp.entrySet()) { + if (PRESIGNED_OPS.contains(e.getKey()) && e.getValue().contains(true)) { + return "workspace credentials were sent to a presigned URL (" + e.getKey() + ")"; + } + } + for (Map.Entry> e : byOp.entrySet()) { + if (!PRESIGNED_OPS.contains(e.getKey()) && e.getValue().contains(false)) { + return "workspace credentials were missing on " + e.getKey(); + } + } + return null; + } + } + + /** A URI's query params, decoded, the first value of each. */ + static Map query(URI uri) { + Map query = new LinkedHashMap<>(); + String raw = uri.getRawQuery(); + if (raw == null || raw.isEmpty()) { + return query; + } + for (String pair : raw.split("&")) { + int eq = pair.indexOf('='); + String key = eq < 0 ? pair : pair.substring(0, eq); + String value = eq < 0 ? "" : pair.substring(eq + 1); + query.putIfAbsent(decode(key), decode(value)); + } + return query; + } + + private static String decode(String s) { + try { + return URLDecoder.decode(s, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } + } + + private static Map jsonObject(byte[] body, String what) + throws IOException, ViolationException { + Object parsed; + try { + parsed = MAPPER.readValue(body, Object.class); + } catch (IOException e) { + throw new ViolationException(what + ": " + e.getMessage()); + } + if (!(parsed instanceof Map)) { + throw new ViolationException(what + " is not a JSON object"); + } + return (Map) parsed; + } + + private static long number(Object value) throws ViolationException { + if (!(value instanceof Number)) { + throw new ViolationException("expected a number, got " + value); + } + return ((Number) value).longValue(); + } + + /** The value of a request header, whatever its case, or null. */ + private static String header(Request request, String name) { + for (Map.Entry e : request.getHeaders().entrySet()) { + if (e.getKey().equalsIgnoreCase(name)) { + return e.getValue(); + } + } + return null; + } + + private static byte[] readBody(Request request) throws IOException { + InputStream stream = request.getBodyStream(); + if (stream == null) { + String text = request.getBodyString(); + return text == null ? new byte[0] : text.getBytes(UTF_8); + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (InputStream in = stream) { + byte[] buf = new byte[8192]; + for (int n; (n = in.read(buf)) >= 0; ) { + out.write(buf, 0, n); + } + } + return out.toByteArray(); + } + + /** Consumes the request body, as a server that rejects a request still receives what was sent. */ + static void drain(Request request) throws IOException { + readBody(request); + } + + /** + * Whether the HTTP client would send a Content-Length header: it does for a body of known length, + * which a stream body has only if the request sets the header. + */ + private static boolean sendsContentLength(Request request) { + return request.getBodyStream() == null || header(request, "Content-Length") != null; + } + + private static Map> headers(String... namesAndValues) { + Map> headers = new LinkedHashMap<>(); + for (int i = 0; i < namesAndValues.length; i += 2) { + headers.put(namesAndValues[i], Collections.singletonList(namesAndValues[i + 1])); + } + return headers; + } + + private static Response jsonResponse(Request request, int status, Object value) + throws IOException { + return response( + request, + status, + headers("Content-Type", "application/json"), + MAPPER.writeValueAsBytes(value)); + } + + private static Response response( + Request request, int status, Map> headers, byte[] body) + throws IOException { + byte[] sent = request.getMethod().equals("HEAD") ? new byte[0] : body; + return new Response( + request, + request.getUri().toURL(), + status, + "status " + status, + headers, + new ByteArrayInputStream(sent)); + } +} diff --git a/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtFakeServerTest.java b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtFakeServerTest.java new file mode 100644 index 000000000..58f04dd09 --- /dev/null +++ b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtFakeServerTest.java @@ -0,0 +1,302 @@ +package com.databricks.sdk.mixin; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.databricks.sdk.core.http.Request; +import com.databricks.sdk.core.http.Response; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** Tests of {@link FilesExtFakeServer}, the FilesExt tests' fake server. */ +public class FilesExtFakeServerTest { + private static final String FILES = + "http://localhost/api/2.0/fs/files/Volumes/catalog/schema/volume/file.bin"; + private static final String RIG_FILES = + "https://rig.example.com/api/3.0/fs/files/Volumes/catalog/schema/volume/file.bin"; + private static final Map AUTH = + Collections.singletonMap("Authorization", "Bearer token"); + + @Test + void presignedMultipartUpload_isStored() throws IOException { + FilesExtFakeServer fake = new FilesExtFakeServer(new FilesExtFakeServer.Config()); + + String initiate = read(send(fake, "POST", FILES + "?action=initiate-upload", "", AUTH)); + assertTrue(initiate.contains("token-offload"), initiate); + String urls = + read( + send( + fake, + "POST", + "http://localhost/api/2.0/fs/create-upload-part-urls", + "{\"session_token\":\"token-offload\",\"start_part_number\":1,\"count\":2}", + AUTH)); + assertTrue(urls.contains("https://cloud.example.com/part/2"), urls); + String[] chunks = {"hello ", "world"}; + for (int i = 0; i < chunks.length; i++) { + int n = i + 1; + Response part = + send( + fake, + "PUT", + "https://cloud.example.com/part/" + n, + chunks[i], + Collections.singletonMap("Content-Length", String.valueOf(chunks[i].length()))); + assertEquals("etag-offload-" + n, part.getFirstHeader("ETag")); + } + Response complete = + send( + fake, + "POST", + FILES + "?action=complete-upload&upload_type=multipart&session_token=token-offload", + "{\"parts\":[{\"part_number\":1,\"etag\":\"etag-offload-1\"}," + + "{\"part_number\":2,\"etag\":\"etag-offload-2\"}]}", + AUTH); + assertEquals(200, complete.getStatusCode(), read(complete)); + + assertArrayEquals("hello world".getBytes(UTF_8), fake.storedFile()); + assertEquals(Collections.singletonList("offload"), fake.endpointsTouched()); + assertNull(fake.credentialViolation()); + assertEquals(Collections.emptyList(), fake.violations()); + } + + @Test + void credentialsOnPresignedUrl_areReported() throws IOException { + FilesExtFakeServer fake = new FilesExtFakeServer(new FilesExtFakeServer.Config()); + + send(fake, "PUT", "https://cloud.example.com/part/1", "x", AUTH); + + assertNotNull(fake.credentialViolation()); + } + + @Test + void aPresignedCredentialLeak_isReportedBeforeAMissingCredential() throws IOException { + FilesExtFakeServer fake = new FilesExtFakeServer(new FilesExtFakeServer.Config()); + // A storage-proxy request without credentials sorts before the presigned one that leaks them. + send( + fake, + "GET", + "https://proxy.example.com/api/2.0/fs/files/Volumes/catalog/schema/volume/file.bin", + "", + noHeaders()); + send(fake, "PUT", "https://cloud.example.com/part/1", "x", AUTH); + + assertEquals( + "workspace credentials were sent to a presigned URL (offload.part)", + fake.credentialViolation()); + } + + @Test + void aLaterMultipartCall_requiresTheSessionToken() throws IOException { + List calls = + Arrays.asList( + "POST " + FILES + "?action=complete-upload&upload_type=multipart&session_token=wrong", + "PUT https://proxy.example.com/api/2.0/fs/files/Volumes/catalog/schema/volume/file.bin" + + "?upload_type=multipart&session_token=wrong&part_number=1", + "POST https://proxy.example.com/api/2.0/fs/files/Volumes/catalog/schema/volume/file.bin" + + "?action=complete-upload&upload_type=multipart&session_token=wrong"); + // With a Content-Length and a parts body, so that only the session_token check can fire. + Map headers = new LinkedHashMap<>(AUTH); + headers.put("Content-Length", "1"); + for (String call : calls) { + FilesExtFakeServer fake = new FilesExtFakeServer(new FilesExtFakeServer.Config()); + String[] methodAndUrl = call.split(" ", 2); + + send(fake, methodAndUrl[0], methodAndUrl[1], "{\"parts\":[]}", headers); + + assertEquals( + Collections.singletonList( + (call.startsWith("PUT") + ? "dp.part" + : call.contains("proxy") ? "dp.complete" : "offload.complete") + + " with session_token \"wrong\""), + fake.violations(), + call); + } + } + + @Test + void faults_applyToTheirCalls() throws IOException { + FilesExtFakeServer.Config cfg = new FilesExtFakeServer.Config(); + cfg.faults.put( + "floor.single", FilesExtFakeServer.onCalls(FilesExtFakeServer.Fault.status(403), 1)); + cfg.faults.put("floor.get", FilesExtFakeServer.always(FilesExtFakeServer.Fault.connection())); + FilesExtFakeServer fake = new FilesExtFakeServer(cfg); + + Response first = send(fake, "PUT", FILES, "x", AUTH); + assertEquals(403, first.getStatusCode()); + assertTrue(read(first).contains("PERMISSION_DENIED")); + assertEquals(200, send(fake, "PUT", FILES, "x", AUTH).getStatusCode()); + assertThrows( + FilesExtFakeServer.FakeNetworkException.class, () -> send(fake, "GET", FILES, "", AUTH)); + assertEquals(2, fake.counts().get("floor.single")); + } + + @Test + void download_servesRangesAndBreaks() throws IOException { + FilesExtFakeServer.Config cfg = new FilesExtFakeServer.Config(); + cfg.downloadContent = "0123456789".getBytes(UTF_8); + cfg.faults.put( + "offload.get", FilesExtFakeServer.onCalls(FilesExtFakeServer.Fault.breakAfter(4), 2)); + FilesExtFakeServer fake = new FilesExtFakeServer(cfg); + + Response ranged = + send( + fake, + "GET", + "https://cloud.example.com/download", + "", + Collections.singletonMap("Range", "bytes=2-5")); + assertEquals(206, ranged.getStatusCode()); + assertEquals("2345", read(ranged)); + InputStream broken = + send(fake, "GET", "https://cloud.example.com/download", "", noHeaders()).getBody(); + byte[] got = new byte[4]; + assertEquals(4, broken.read(got)); + assertEquals("0123", new String(got, UTF_8)); + assertThrows(FilesExtFakeServer.FakeBrokenTransferException.class, broken::read); + Response pastTheEnd = + send( + fake, + "GET", + "https://cloud.example.com/download", + "", + Collections.singletonMap("Range", "bytes=20-")); + assertEquals(206, pastTheEnd.getStatusCode()); + assertEquals("", read(pastTheEnd)); + assertEquals(Arrays.asList("bytes=2-5", "", "bytes=20-"), fake.ranges("offload")); + } + + @Test + void endpointsApi_answersTheConfiguredList() throws IOException { + String endpoints = "http://localhost/api/2.0/fs/endpoints"; + FilesExtFakeServer without = new FilesExtFakeServer(new FilesExtFakeServer.Config()); + assertEquals(404, send(without, "GET", endpoints, "", AUTH).getStatusCode()); + + FilesExtFakeServer.Config cfg = new FilesExtFakeServer.Config(); + Map entry = new LinkedHashMap<>(); + entry.put("api", "IO_OFFLOAD"); + entry.put("scheme", "http"); + entry.put("hostname", "localhost"); + cfg.endpoints = Collections.singletonList(entry); + String body = read(send(new FilesExtFakeServer(cfg), "GET", endpoints, "", AUTH)); + assertTrue(body.contains("IO_OFFLOAD"), body); + } + + @Test + void unexpectedRequest_isAViolation() throws IOException { + FilesExtFakeServer fake = new FilesExtFakeServer(new FilesExtFakeServer.Config()); + + Response response = send(fake, "GET", "http://localhost/api/2.0/somewhere", "", AUTH); + + assertEquals(400, response.getStatusCode()); + assertEquals(1, fake.violations().size(), fake.violations().toString()); + } + + @Test + void hostMetadataRequest_isAnswered404AndIsNotAnOperation() throws IOException { + FilesExtFakeServer fake = new FilesExtFakeServer(new FilesExtFakeServer.Config()); + + Response response = + send( + fake, + "GET", + "http://localhost" + FilesExtFakeServer.HOST_METADATA_PATH, + "", + noHeaders()); + + assertEquals(404, response.getStatusCode()); + assertEquals(Collections.emptyMap(), fake.counts()); + assertEquals(Collections.emptyList(), fake.violations()); + assertEquals( + Collections.singletonList("GET " + FilesExtFakeServer.HOST_METADATA_PATH), + fake.sdkRequests()); + } + + @Test + void filesApi3_requiresTheUploadId() throws IOException { + FilesExtFakeServer fake = new FilesExtFakeServer(new FilesExtFakeServer.Config()); + // With a Content-Length, so that only the upload_id check can fire. + Map headers = new LinkedHashMap<>(AUTH); + headers.put("Content-Length", "1"); + + send(fake, "PUT", RIG_FILES + "?part_number=1&upload_id=wrong", "x", headers); + + assertEquals(1, fake.violations().size(), fake.violations().toString()); + assertTrue(fake.violations().get(0).contains("upload_id"), fake.violations().toString()); + } + + @Test + void filesApi3_requiresAContentLength() throws IOException { + FilesExtFakeServer fake = new FilesExtFakeServer(new FilesExtFakeServer.Config()); + + send(fake, "PUT", RIG_FILES + "?part_number=1&upload_id=upload-rig", "x", AUTH); + + assertEquals(1, fake.violations().size(), fake.violations().toString()); + assertTrue(fake.violations().get(0).contains("Content-Length"), fake.violations().toString()); + } + + @Test + void partPuts_requireAContentLength() throws IOException { + FilesExtFakeServer fake = new FilesExtFakeServer(new FilesExtFakeServer.Config()); + send(fake, "POST", FILES + "?action=initiate-upload", "", AUTH); + send( + fake, + "POST", + "http://localhost/api/2.0/fs/create-upload-part-urls", + "{\"session_token\":\"token-offload\",\"start_part_number\":1,\"count\":1}", + AUTH); + + send(fake, "PUT", "https://cloud.example.com/part/1", "x", noHeaders()); + send( + fake, + "PUT", + "https://proxy.example.com/api/2.0/fs/files/Volumes/catalog/schema/volume/file.bin" + + "?upload_type=multipart&session_token=token-dp&part_number=1", + "x", + AUTH); + + assertEquals(2, fake.violations().size(), fake.violations().toString()); + assertTrue(fake.violations().get(0).contains("offload.part"), fake.violations().toString()); + assertTrue(fake.violations().get(1).contains("dp.part"), fake.violations().toString()); + } + + private static Map noHeaders() { + return Collections.emptyMap(); + } + + private static Response send( + FilesExtFakeServer fake, String method, String url, String body, Map headers) + throws IOException { + Request request = + body.isEmpty() + ? new Request(method, url) + : new Request(method, url, new ByteArrayInputStream(body.getBytes(UTF_8))); + request.withHeaders(headers); + return fake.execute(request); + } + + private static String read(Response response) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buf = new byte[1024]; + try (InputStream in = response.getBody()) { + for (int n; (n = in.read(buf)) >= 0; ) { + out.write(buf, 0, n); + } + } + return new String(out.toByteArray(), UTF_8); + } +} diff --git a/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtPresignedTest.java b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtPresignedTest.java new file mode 100644 index 000000000..4866e7ffe --- /dev/null +++ b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtPresignedTest.java @@ -0,0 +1,510 @@ +package com.databricks.sdk.mixin; + +import static com.databricks.sdk.mixin.FilesExtClientHarness.PATH; +import static com.databricks.sdk.mixin.FilesExtClientHarness.awaitUninterruptibly; +import static com.databricks.sdk.mixin.FilesExtClientHarness.response; +import static com.databricks.sdk.mixin.FilesExtClientHarness.transferThreads; +import static com.databricks.sdk.mixin.FilesExtClientHarness.upload; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.databricks.sdk.core.DatabricksError; +import com.databricks.sdk.core.DatabricksException; +import com.databricks.sdk.core.error.platform.PermissionDenied; +import com.databricks.sdk.core.utils.FakeTimer; +import com.databricks.sdk.mixin.FilesExtEndpoint.Kind; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * The presigned endpoint client, in the built-in order before the workspace, against the {@link + * FilesExtFakeServer}. + */ +public class FilesExtPresignedTest { + private static final byte[] TEN = "0123456789".getBytes(UTF_8); + + @TempDir Path tempDir; + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void presigned_multipartUpload_isStoredWithValidRequests(boolean parallel) throws IOException { + FilesExtClientHarness h = new FilesExtClientHarness(); + + upload(h.builtInOrder(), TEN, parallel, 4); + + assertArrayEquals(TEN, h.fake.storedFile()); + assertEquals(Collections.singletonList("offload"), h.fake.endpointsTouched()); + assertEquals(Integer.valueOf(3), h.fake.counts().get("offload.part")); + assertEquals(Integer.valueOf(1), h.fake.counts().get("offload.complete")); + h.assertNoViolations(); + } + + @Test + void presignedInitiateFailure_walksToTheWorkspace() throws IOException { + FilesExtClientHarness h = new FilesExtClientHarness(); + h.cfg.faults.put( + "offload.initiate", FilesExtFakeServer.always(FilesExtFakeServer.Fault.status(403))); + + upload(h.builtInOrder(), TEN, false, 4); + + assertArrayEquals(TEN, h.fake.storedFile()); + assertEquals(Arrays.asList("offload", "floor"), h.fake.endpointsTouched()); + assertFalse(h.fake.aborted("offload")); + h.assertNoViolations(); + } + + @Test + void partFailureAfterCommit_raisesAndAbortsOnce() { + FilesExtClientHarness h = new FilesExtClientHarness(); + h.cfg.faults.put( + "offload.part", FilesExtFakeServer.onCalls(FilesExtFakeServer.Fault.status(403), 2)); + + DatabricksError e = + assertThrows(DatabricksError.class, () -> upload(h.builtInOrder(), TEN, false, 4)); + + assertTrue(e instanceof PermissionDenied, e.toString()); + assertEquals(Integer.valueOf(1), h.fake.counts().get("offload.abort")); + assertNull(h.fake.counts().get("floor.single")); + h.assertNoViolations(); + } + + @Test + void expiredPartUrl_isRequestedAgainAndTheUploadSucceeds() throws IOException { + AtomicInteger expiries = new AtomicInteger(); + FilesExtClientHarness h = + new FilesExtClientHarness( + fake -> + request -> { + if (request.getUri().getHost().equals("cloud.example.com") + && expiries.getAndIncrement() == 0) { + FilesExtFakeServer.drain(request); + return response( + request, + 403, + "AccessDeniedRequest has expired", + Collections.emptyMap()); + } + return fake.execute(request); + }); + + upload(h.builtInOrder(), TEN, false, 4); + + assertArrayEquals(TEN, h.fake.storedFile()); + // One URL per part, as the batch is 1, and the first part's again once it expired. + assertEquals(Integer.valueOf(4), h.fake.counts().get("offload.part-urls")); + h.assertNoViolations(); + } + + @Test + void partUrlThatKeepsExpiring_walksAfterThreeRefreshes() { + FilesExtClientHarness h = + new FilesExtClientHarness( + fake -> + request -> { + if (request.getUri().getHost().equals("cloud.example.com")) { + FilesExtFakeServer.drain(request); + return response( + request, + 403, + "ExpiredToken", + Collections.emptyMap()); + } + return fake.execute(request); + }); + FilesExtPresigned.PresignedClient presigned = h.presigned(); + + IllegalArgumentException e = + assertThrows( + IllegalArgumentException.class, + () -> + FilesExtUploadWalk.upload( + Collections.singletonList(presigned), + FilesExtUploadData.fromStream(new ByteArrayInputStream(TEN)), + PATH, + null, + 4, + 1, + false, + null, + 4)); + + assertEquals("Unsuccessful chunk upload: upload URL expired after 3 retries", e.getMessage()); + assertEquals(Integer.valueOf(4), h.fake.counts().get("offload.part-urls")); + } + + @Test + void aMalformedPartUrlAnswer_namesTheBadEntryWithoutEchoingTheUrls() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + String signed = "https://cloud.example.com/part/1?X-Amz-Signature=secret-signature"; + List answers = + Arrays.asList( + "{\"upload_part_urls\":[{\"part_number\":1,\"url\":\"" + + signed + + "\"},{\"part_number\":2}]}", + "{\"upload_part_urls\":[{\"part_number\":1,\"url\":\"" + + signed + + "\"},{\"url\":\"" + + signed + + "\"}]}", + "{\"upload_part_urls\":[],\"other\":\"" + signed + "\"}"); + List messages = new ArrayList<>(); + for (String answer : answers) { + messages.add( + assertThrows( + IllegalArgumentException.class, + () -> FilesExtPresigned.PresignedSession.parseUrls(mapper.readTree(answer))) + .getMessage()); + } + + assertEquals( + Arrays.asList( + "Unexpected server response: upload_part_urls[1] has no url", + "Unexpected server response: upload_part_urls[1] has no integer part_number", + "Unexpected server response: upload_part_urls is missing, empty or not a list"), + messages); + } + + static Stream cloudErrorsOnAPart() { + return Stream.of( + Arguments.of( + "S3 XML error with the signing details", + "SignatureDoesNotMatchThe request signature we calculated" + + " does not match the signature you provided." + + "AKIAEXAMPLE" + + "AWS4-HMAC-SHA256 secret-scope" + + "secret-signature" + + "PUT /part/1 X-Amz-Signature=secret-signature" + + "" + + "", + "Unsuccessful chunk upload. Response status: 403, code: SignatureDoesNotMatch, message:" + + " The request signature we calculated does not match the signature you" + + " provided."), + Arguments.of( + "XML error whose message echoes the signed URL", + "AccessDeniedDenied for" + + " https://cloud.example.com/part/1?X-Amz-Signature=secret-signature, check the" + + " policy", + "Unsuccessful chunk upload. Response status: 403, code: AccessDenied, message: Denied" + + " for https://cloud.example.com/part/1 check the policy"), + Arguments.of( + "JSON error echoing the signed URL", + "{\"error_code\":\"PERMISSION_DENIED\",\"message\":\"denied:" + + " https://cloud.example.com/part/1?X-Amz-Signature=secret-signature\"}", + "Unsuccessful chunk upload. Response status: 403")); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("cloudErrorsOnAPart") + void aCloudErrorOnAPart_keepsTheProvidersCodeAndMessageOnly( + String name, String body, String expected) { + FilesExtClientHarness h = + new FilesExtClientHarness( + fake -> + request -> { + if (request.getUri().getHost().equals("cloud.example.com")) { + FilesExtFakeServer.drain(request); + return response(request, 403, body, Collections.emptyMap()); + } + return fake.execute(request); + }); + + DatabricksError e = + assertThrows( + DatabricksError.class, + () -> upload(Collections.singletonList(h.presigned()), TEN, false, 4)); + + assertEquals(expected, e.getMessage()); + } + + @Test + void workspaceCalls_waitTheServersRetryAfter() throws IOException { + AtomicBoolean throttled = new AtomicBoolean(); + FilesExtClientHarness h = + new FilesExtClientHarness( + fake -> + request -> { + if (request.getUri().toString().contains("action=initiate-upload") + && throttled.compareAndSet(false, true)) { + return response( + request, + 429, + "{\"error_code\":\"TOO_MANY_REQUESTS\",\"message\":\"slow down\"}", + Collections.singletonMap("Retry-After", "7")); + } + return fake.execute(request); + }); + + upload(h.builtInOrder(), TEN, false, 4); + + assertArrayEquals(TEN, h.fake.storedFile()); + long waited = h.timer.getCurrentTime(); + assertTrue(waited >= 7000 && waited < 8000, waited + " ms"); + } + + @ParameterizedTest(name = "in-flight PUT answers {0}") + @ValueSource(strings = {"200", "an expired URL"}) + void interruptedParallelUpload_overTheHttpClient_waitsForTheInFlightPut(String inFlightAnswer) + throws Exception { + CountDownLatch release = new CountDownLatch(1); + CountDownLatch inFlight = new CountDownLatch(2); + AtomicInteger partsAfterInterrupt = new AtomicInteger(); + AtomicBoolean interruptSent = new AtomicBoolean(); + FilesExtClientHarness h = + new FilesExtClientHarness( + fake -> + request -> { + if (Thread.currentThread().isInterrupted()) { + // As an interrupt-sensitive HTTP client would. + throw new IOException("refused on an interrupted thread"); + } + boolean part = request.getUri().getHost().equals("cloud.example.com"); + if (part && !request.getUri().getPath().endsWith("/1")) { + if (interruptSent.get()) { + partsAfterInterrupt.incrementAndGet(); + } + inFlight.countDown(); + // A request only the server ends: an HTTP client read isn't interruptible. + awaitUninterruptibly(release); + if (inFlightAnswer.equals("an expired URL")) { + FilesExtFakeServer.drain(request); + return response( + request, + 403, + "ExpiredToken", + Collections.emptyMap()); + } + } + return fake.execute(request); + }); + Path file = Files.write(tempDir.resolve("source"), new byte[40]); + FileChannel channel = FileChannel.open(file, StandardOpenOption.READ); + AtomicReference thrown = new AtomicReference<>(); + AtomicBoolean interruptedOnReturn = new AtomicBoolean(); + Thread caller = + new Thread( + () -> { + try { + FilesExtUploadWalk.upload( + h.builtInOrder(), + FilesExtUploadData.fromChannel(channel), + PATH, + null, + 4, + 1, + true, + 2, + 4); + } catch (Throwable t) { + thrown.set(t); + } + interruptedOnReturn.set(Thread.currentThread().isInterrupted()); + }); + caller.start(); + assertTrue(inFlight.await(10, TimeUnit.SECONDS)); + + interruptSent.set(true); + caller.interrupt(); + caller.join(500); + assertTrue(caller.isAlive()); + release.countDown(); + caller.join(10_000); + + assertFalse(caller.isAlive()); + assertTrue(thrown.get() instanceof DatabricksException, String.valueOf(thrown.get())); + assertEquals("Current thread was interrupted", thrown.get().getMessage()); + assertTrue(interruptedOnReturn.get()); + assertEquals(0, partsAfterInterrupt.get()); + assertEquals(Integer.valueOf(1), h.fake.counts().get("offload.abort")); + assertNull(h.fake.counts().get("offload.complete")); + assertTrue(channel.isOpen()); + assertEquals(Collections.emptyList(), transferThreads()); + h.assertNoViolations(); + channel.close(); + } + + @Test + void malformedControlAnswer_walksWithoutRetrying() throws IOException { + AtomicInteger initiates = new AtomicInteger(); + FilesExtClientHarness counting = + new FilesExtClientHarness( + fake -> + request -> { + if (request.getUri().toString().contains("action=initiate-upload")) { + initiates.incrementAndGet(); + return response(request, 200, "proxy", Collections.emptyMap()); + } + return fake.execute(request); + }); + + upload(counting.builtInOrder(), TEN, false, 4); + + assertArrayEquals(TEN, counting.fake.storedFile()); + assertEquals(1, initiates.get()); + assertEquals(Collections.singletonList("floor"), counting.fake.endpointsTouched()); + } + + @Test + void cloudThrottling_backsOff_ignoringTheDefaultRetryAfter() throws IOException { + List part2Attempts = new ArrayList<>(); + AtomicReference timer = new AtomicReference<>(); + FilesExtClientHarness h = + new FilesExtClientHarness( + fake -> + request -> { + if (request.getUri().toString().equals("https://cloud.example.com/part/2")) { + part2Attempts.add(timer.get().getCurrentTime()); + if (part2Attempts.size() <= 2) { + FilesExtFakeServer.drain(request); + return response( + request, + 429, + "SlowDown", + Collections.emptyMap()); + } + } + return fake.execute(request); + }); + timer.set(h.timer); + + upload(h.builtInOrder(), TEN, false, 4); + + assertArrayEquals(TEN, h.fake.storedFile()); + assertEquals(3, part2Attempts.size()); + // min(10, attempt) seconds plus jitter: 1 s, then 2 s. The 1 s default would make both 1 s. + long second = part2Attempts.get(2) - part2Attempts.get(1); + assertTrue(second >= 2000 && second < 3000, second + " ms"); + } + + @Test + void firstPartFailureBeforeCommit_retriesOnceThenWalksAndAborts() throws IOException { + FilesExtClientHarness h = new FilesExtClientHarness(); + h.cfg.faults.put( + "offload.part", + call -> + call == 1 + ? FilesExtFakeServer.Fault.status(503) + : call == 2 ? FilesExtFakeServer.Fault.status(503) : null); + + upload(h.builtInOrder(), TEN, false, 4); + + assertArrayEquals(TEN, h.fake.storedFile()); + // One retry before commit, then the workspace. + assertEquals(Integer.valueOf(2), h.fake.counts().get("offload.part")); + assertEquals(Integer.valueOf(1), h.fake.counts().get("offload.abort")); + assertEquals(Integer.valueOf(1), h.fake.counts().get("floor.single")); + h.assertNoViolations(); + } + + @Test + void completeFailure_raisesAndAbortsOnce() { + FilesExtClientHarness h = new FilesExtClientHarness(); + h.cfg.faults.put( + "offload.complete", FilesExtFakeServer.always(FilesExtFakeServer.Fault.status(403))); + + assertThrows(PermissionDenied.class, () -> upload(h.builtInOrder(), TEN, false, 4)); + + assertEquals(Integer.valueOf(1), h.fake.counts().get("offload.abort")); + h.assertNoViolations(); + } + + @ParameterizedTest(name = "{0} fails, abort gets {1}") + @CsvSource({"part, 503", "part, connection error", "complete, 503", "complete, connection error"}) + void failingAbort_isSentOnce_andTheUploadsErrorSurfaces(String failing, String abortFault) { + FilesExtClientHarness h = new FilesExtClientHarness(); + if (failing.equals("part")) { + h.cfg.faults.put( + "offload.part", FilesExtFakeServer.onCalls(FilesExtFakeServer.Fault.status(403), 2)); + } else { + h.cfg.faults.put( + "offload.complete", FilesExtFakeServer.always(FilesExtFakeServer.Fault.status(403))); + } + h.cfg.faults.put( + "offload.abort", + FilesExtFakeServer.always( + abortFault.equals("503") + ? FilesExtFakeServer.Fault.status(503) + : FilesExtFakeServer.Fault.connection())); + + assertThrows(PermissionDenied.class, () -> upload(h.builtInOrder(), TEN, false, 4)); + + assertEquals(Integer.valueOf(1), h.fake.counts().get("offload.abort")); + assertNull(h.fake.counts().get("floor.single")); + } + + static Stream urlExpiryAnswers() { + return Stream.of( + Arguments.of("S3 ExpiredToken", 400, "ExpiredToken", true), + Arguments.of( + "Azure signature out of its time frame", + 403, + "AuthenticationFailedSignature not valid" + + " in the specified time frame: x", + true), + Arguments.of( + "GCS request has expired", + 403, + "AccessDeniedRequest has expired", + true), + Arguments.of( + "access denied for another reason", + 403, + "AccessDeniedAccess Denied", + false), + Arguments.of("a 500", 500, "ExpiredToken", false), + Arguments.of("not XML", 403, "not xml", false), + Arguments.of( + "a Code that isn't the root's own child", + 403, + "
ExpiredToken
", + false), + Arguments.of( + "a DOCTYPE, refused so there are no external entities", + 403, + "]>&x;", + false)); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("urlExpiryAnswers") + void isUrlExpired_knowsEachCloudsError(String name, int status, String body, boolean expired) { + assertEquals(expired, FilesExtPresigned.isUrlExpired(status, body)); + } + + @Test + void presignedClient_takesOnlyTheWorkspaceHost() { + FilesExtClientHarness h = new FilesExtClientHarness(); + FilesExtEndpoint other = + new FilesExtEndpoint(Kind.IO_OFFLOAD, "https://proxy.example.com", true); + + assertThrows( + IllegalArgumentException.class, + () -> new FilesExtPresigned.PresignedClient(h.transfer, other)); + } +} diff --git a/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtResponseRecorderTest.java b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtResponseRecorderTest.java new file mode 100644 index 000000000..ce1448c32 --- /dev/null +++ b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtResponseRecorderTest.java @@ -0,0 +1,444 @@ +package com.databricks.sdk.mixin; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.databricks.sdk.core.ApiClient; +import com.databricks.sdk.core.CredentialsProvider; +import com.databricks.sdk.core.DatabricksConfig; +import com.databricks.sdk.core.DatabricksError; +import com.databricks.sdk.core.DummyCredentialsProvider; +import com.databricks.sdk.core.HeaderFactory; +import com.databricks.sdk.core.http.HttpClient; +import com.databricks.sdk.core.http.Request; +import com.databricks.sdk.core.http.Response; +import com.databricks.sdk.core.utils.FakeTimer; +import com.databricks.sdk.mixin.FilesExtRetry.Budget; +import com.databricks.sdk.mixin.FilesExtRetry.RequestFailed; +import com.databricks.sdk.mixin.FilesExtRetry.Result; +import com.databricks.sdk.mixin.FilesExtRetry.Send; +import com.databricks.sdk.mixin.FilesExtRetry.TransferStatus; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InterruptedIOException; +import java.time.Duration; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Deque; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * The single-attempt workspace client's responses reach the retry loop with what the retry needs: a + * 429 or 503 waits the server's Retry-After. + */ +public class FilesExtResponseRecorderTest { + private static final String FILES_PATH = "/api/2.0/fs/files/Volumes/catalog/schema/volume/f"; + + static List firstWait() { + Answer transientError = new Answer(500, "7"); + transientError.message = "Unexpected error"; + return Arrays.asList( + Arguments.of("429 with Retry-After 7", new Answer(429, "7"), 7000L), + Arguments.of("503 with Retry-After 7", new Answer(503, "7"), 7000L), + Arguments.of("429 without Retry-After", new Answer(429, null), 1000L), + Arguments.of("503 without Retry-After", new Answer(503, null), 1000L), + // Only integer seconds are read, not HTTP dates. + Arguments.of("429 with Retry-After soon", new Answer(429, "soon"), 1000L), + Arguments.of( + "429 with an HTTP date", new Answer(429, "Wed, 21 Oct 2026 07:28:00 GMT"), 1000L), + Arguments.of("429 with an empty Retry-After", new Answer(429, ""), 1000L), + // Only a 429 or 503 carries Retry-After: a 502 retries on the common rows, and a 500 with + // a transient message on the API client's rules, both with the first backoff. + Arguments.of("502 ignores Retry-After", new Answer(502, "7"), 1000L), + Arguments.of("transient 500 ignores Retry-After", transientError, 1000L)); + } + + @ParameterizedTest(name = "{0}") + @MethodSource + void firstWait(String name, Answer first, long wantMillis) { + assertWaitsAbout(wantMillis, firstWait(first)); + } + + @Test + void errorResponse_failsWithItsStatusAndRetryAfter() { + Server server = new Server(new Answer(429, "30")); + FilesExt files = files(server); + + RequestFailed failure = assertThrows(RequestFailed.class, () -> workspaceGet(files).send()); + + assertEquals(Integer.valueOf(429), failure.statusCode); + assertEquals(Long.valueOf(30), failure.retryAfterSeconds); + assertNull(failure.decision); + assertTrue(failure.error instanceof DatabricksError, failure.error.toString()); + } + + @Test + void errorResponse_failsWithTheResponsesStatus_notItsErrorClasss() { + Answer precondition = new Answer(412, null); + precondition.errorCode = "UNKNOWN"; + FilesExt files = files(new Server(precondition)); + + RequestFailed failure = assertThrows(RequestFailed.class, () -> workspaceGet(files).send()); + + // The typed error carries its class's canonical status; the response said 412. + assertNotEquals(412, ((DatabricksError) failure.error).getStatusCode()); + assertEquals(Integer.valueOf(412), failure.statusCode); + assertEquals(FilesExtRetry.Decision.RAISE, FilesExtRetry.commonDecision(failure)); + } + + @Test + void noResponse_failsWithTheApiClientsOwnError_evenAfterAnErrorResponse() { + Server server = new Server(new Answer(429, "30"), Answer.dropped()); + FilesExt files = files(server); + assertThrows(RequestFailed.class, () -> workspaceGet(files).send()); + + DatabricksError error = assertThrows(DatabricksError.class, () -> workspaceGet(files).send()); + + // Not the previous call's answer: a transport failure is not a response. + assertEquals("IO_ERROR", error.getErrorCode()); + assertEquals(0, files.workspaceResponses().pending()); + } + + @Test + void aFailureBeforeTheRequest_doesNotTakeAnEarlierAnswer() { + DatabricksError beforeTheRequest = new DatabricksError("UNAUTHENTICATED", "no token", 401); + AtomicBoolean failAuth = new AtomicBoolean(); + DatabricksConfig config = + new DatabricksConfig() + .setHost("http://localhost") + .setCredentialsProvider( + new CredentialsProvider() { + @Override + public String authType() { + return "test"; + } + + @Override + public HeaderFactory configure(DatabricksConfig c) { + return () -> { + if (failAuth.get()) { + throw beforeTheRequest; + } + return Collections.singletonMap("Authorization", "Basic test"); + }; + } + }) + .setHttpClient(new Server(new Answer(429, "30"))); + FilesExt files = new FilesExt(new ApiClient(config), config); + assertThrows(RequestFailed.class, () -> workspaceGet(files).send()); + failAuth.set(true); + + Exception e = assertThrows(Exception.class, () -> workspaceGet(files).send()); + + // The authentication failure itself, not a RequestFailed with the earlier 429's answer. + assertFalse(e instanceof RequestFailed, e.toString()); + boolean causedByIt = false; + for (Throwable t = e; t != null; t = t.getCause()) { + causedByIt |= t == beforeTheRequest; + } + assertTrue(causedByIt, e.toString()); + assertEquals(0, files.workspaceResponses().pending()); + } + + @Test + void everyRequestReachesTheConfiguredHttpClient() { + Server server = new Server(new Answer(429, "1"), new Answer(503, null)); + FilesExt files = files(server); + + Result result = + FilesExtRetry.retry( + workspaceGet(files), + FilesExtRetry::commonDecision, + new Budget(null, Duration.ofMinutes(5)), + new TransferStatus(true, 0), + new FakeTimer()); + + assertFalse(result.failed()); + assertEquals(3, server.fileRequests.size()); + for (Request request : server.fileRequests) { + assertTrue( + request.getHeaders().containsKey("Authorization"), request.getHeaders().toString()); + } + } + + @Test + void retryAfterSeconds_readsIntegerSecondsOnly() { + assertEquals( + Long.valueOf(30), FilesExtResponseRecorder.retryAfterSeconds(response(429, " 30 "))); + assertEquals(Long.valueOf(1), FilesExtResponseRecorder.retryAfterSeconds(response(503, "1.5"))); + assertNull(FilesExtResponseRecorder.retryAfterSeconds(response(500, "30"))); + assertNull(FilesExtResponseRecorder.retryAfterSeconds(response(200, "30"))); + } + + /** How long the retry loop waits after a workspace call that got {@code first}, then a 200. */ + private static long firstWait(Answer first) { + Server server = new Server(first); + FilesExt files = files(server); + FakeTimer clock = new FakeTimer(); + + Result result = + FilesExtRetry.retry( + workspaceGet(files), + FilesExtRetry::commonDecision, + new Budget(2, Duration.ofMinutes(5)), + new TransferStatus(true, 0), + clock); + + assertFalse(result.failed(), () -> String.valueOf(result.failure.error)); + assertEquals(2, server.fileRequests.size()); + return clock.getCurrentTime(); + } + + private static void assertWaitsAbout(long millis, long waited) { + assertTrue(waited >= millis && waited < millis + 1000, "waited " + waited + " ms"); + } + + private static Send workspaceGet(FilesExt files) { + return () -> get(files, FILES_PATH).value; + } + + private static FilesExtRetry.Answered get(FilesExt files, String path) throws Exception { + return FilesExtRetry.onWorkspace( + files.singleAttemptApiClient(), + files.workspaceResponses(), + new Request("GET", path), + Void.class); + } + + @Test + void theApiClient_handsTheCallersOwnRequestToItsHttpClient() throws IOException { + // The recorder keys answers by request identity: an API client that copied the request would + // lose every Retry-After, so this fails loudly instead. + List seen = new ArrayList<>(); + Server server = new Server(); + FilesExt files = + files( + request -> { + seen.add(request); + return server.execute(request); + }); + Request request = new Request("GET", FILES_PATH); + + files.singleAttemptApiClient().execute(request, Void.class); + + assertTrue(seen.stream().anyMatch(r -> r == request), "the API client copied the request"); + } + + @Test + void aSuccess_readsItsOwnStatus_andForgetsIt() throws Exception { + FilesExt files = files(new Server(new Answer(206, null))); + + FilesExtRetry.Answered answered = get(files, FILES_PATH); + + assertEquals(206, answered.statusCode); + assertEquals(0, files.workspaceResponses().pending()); + } + + @Test + void everyPath_forgetsItsAnswer() { + // A DatabricksError response, a dropped connection, and an unexpected error from the client. + FilesExt files = files(new Server(new Answer(429, "3"), Answer.dropped())); + assertThrows(RequestFailed.class, () -> get(files, FILES_PATH)); + assertEquals(0, files.workspaceResponses().pending()); + assertThrows(DatabricksError.class, () -> get(files, FILES_PATH)); + assertEquals(0, files.workspaceResponses().pending()); + + FilesExt broken = + files( + request -> { + if (request.getUri().getPath().startsWith("/api/2.0/fs/files")) { + throw new IllegalStateException("bug"); + } + return new Server().execute(request); + }); + assertThrows(IllegalStateException.class, () -> get(broken, FILES_PATH)); + assertEquals(0, broken.workspaceResponses().pending()); + } + + @Test + void anInterruptedCall_forgetsItsAnswer() { + FilesExt files = + files( + request -> { + if (request.getUri().getPath().startsWith("/api/2.0/fs/files")) { + Thread.currentThread().interrupt(); + throw new InterruptedIOException("interrupted"); + } + return new Server().execute(request); + }); + try { + assertThrows(RuntimeException.class, () -> get(files, FILES_PATH)); + } finally { + Thread.interrupted(); + } + assertEquals(0, files.workspaceResponses().pending()); + } + + @Test + void requestsNobodyExpects_areNotRecorded() throws IOException { + FilesExt files = files(new Server(new Answer(429, "3"))); + + assertThrows( + DatabricksError.class, + () -> files.singleAttemptApiClient().execute(new Request("GET", FILES_PATH), Void.class)); + + assertEquals(0, files.workspaceResponses().pending()); + } + + @Test + void concurrentCalls_eachReadTheirOwnAnswer() throws Exception { + Map byPath = new HashMap<>(); + byPath.put("/a", new Answer(429, "3")); + byPath.put("/b", new Answer(429, "7")); + byPath.put("/c", new Answer(503, null)); + byPath.put("/d", new Answer(200, null)); + CyclicBarrier together = new CyclicBarrier(4); + FilesExt files = + files( + request -> { + String path = request.getUri().getPath(); + for (Map.Entry e : byPath.entrySet()) { + if (path.endsWith(e.getKey())) { + try { + // All four are in flight at once before any answers. + together.await(10, TimeUnit.SECONDS); + } catch (Exception ex) { + throw new IOException(ex); + } + return new Server(e.getValue()).execute(request); + } + } + return new Server().execute(request); + }); + ExecutorService pool = Executors.newFixedThreadPool(4); + try { + Map> results = new HashMap<>(); + for (String path : byPath.keySet()) { + results.put( + path, + pool.submit( + () -> { + try { + return get(files, FILES_PATH + path).statusCode; + } catch (RequestFailed e) { + return e; + } + })); + } + + assertEquals(Long.valueOf(3), ((RequestFailed) results.get("/a").get()).retryAfterSeconds); + assertEquals(Long.valueOf(7), ((RequestFailed) results.get("/b").get()).retryAfterSeconds); + RequestFailed unavailable = (RequestFailed) results.get("/c").get(); + assertEquals(Integer.valueOf(503), unavailable.statusCode); + assertEquals(Long.valueOf(1), unavailable.retryAfterSeconds); + assertEquals(200, results.get("/d").get()); + assertEquals(0, files.workspaceResponses().pending()); + } finally { + pool.shutdownNow(); + } + } + + /** What new WorkspaceClient(config) builds. */ + private static FilesExt files(HttpClient httpClient) { + DatabricksConfig config = + new DatabricksConfig() + .setHost("http://localhost") + .setCredentialsProvider(new DummyCredentialsProvider()) + .setHttpClient(httpClient); + FilesExt files = new FilesExt(new ApiClient(config), config); + assertTrue(files.hasTransferExtension()); + return files; + } + + private static Response response(int status, String retryAfter) { + Request request = new Request("GET", "http://localhost" + FILES_PATH); + Map> headers = new HashMap<>(); + headers.put("retry-after", Collections.singletonList(retryAfter)); + return new Response(request, status, "status " + status, headers); + } + + /** One queued answer of the fake server. */ + private static final class Answer { + final int status; + final String retryAfter; + String message = "no"; + String errorCode = "TEMPORARILY_UNAVAILABLE"; + boolean dropped; + + Answer(int status, String retryAfter) { + this.status = status; + this.retryAfter = retryAfter; + } + + static Answer dropped() { + Answer a = new Answer(0, null); + a.dropped = true; + return a; + } + } + + /** + * Answers the Files API with the queued answers, then 200, and the host-metadata request with + * 404, recording the Files API requests. + */ + private static final class Server implements HttpClient { + private final Deque answers = new ArrayDeque<>(); + final List fileRequests = new ArrayList<>(); + + Server(Answer... queued) { + Collections.addAll(answers, queued); + } + + @Override + public Response execute(Request in) throws IOException { + boolean files = in.getUri().getPath().startsWith("/api/2.0/fs/files"); + Answer answer = files ? answers.poll() : new Answer(404, null); + if (files) { + fileRequests.add(in); + } + if (answer != null && answer.dropped) { + throw new IOException("connection reset"); + } + int code = answer == null ? 200 : answer.status; + String body = + code == 200 + ? "" + : "{\"error_code\": \"" + + answer.errorCode + + "\", \"message\": \"" + + answer.message + + "\"}"; + Map> headers = new HashMap<>(); + headers.put("Content-Type", Collections.singletonList("application/json")); + if (answer != null && answer.retryAfter != null) { + headers.put("Retry-After", Collections.singletonList(answer.retryAfter)); + } + return new Response( + in, + in.getUri().toURL(), + code, + "status " + code, + headers, + new ByteArrayInputStream(body.getBytes(UTF_8))); + } + } +} diff --git a/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtRetryTest.java b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtRetryTest.java new file mode 100644 index 000000000..e00aa21ed --- /dev/null +++ b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtRetryTest.java @@ -0,0 +1,703 @@ +package com.databricks.sdk.mixin; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.databricks.sdk.core.DatabricksError; +import com.databricks.sdk.core.DatabricksException; +import com.databricks.sdk.core.error.platform.AlreadyExists; +import com.databricks.sdk.core.utils.Timer; +import com.databricks.sdk.mixin.FilesExtRetry.Budget; +import com.databricks.sdk.mixin.FilesExtRetry.Decision; +import com.databricks.sdk.mixin.FilesExtRetry.EndpointClient; +import com.databricks.sdk.mixin.FilesExtRetry.Failure; +import com.databricks.sdk.mixin.FilesExtRetry.RequestFailed; +import com.databricks.sdk.mixin.FilesExtRetry.Result; +import com.databricks.sdk.mixin.FilesExtRetry.Send; +import com.databricks.sdk.mixin.FilesExtRetry.SourceReadFailed; +import com.databricks.sdk.mixin.FilesExtRetry.TransferStatus; +import com.databricks.sdk.mixin.FilesExtRetry.UrlExpired; +import java.io.IOException; +import java.net.ConnectException; +import java.net.SocketTimeoutException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.http.ConnectionClosedException; +import org.apache.http.TruncatedChunkException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +/** The retry loop and endpoint walk of the Files transfer extension, on a fake clock. */ +public class FilesExtRetryTest { + private static final Budget UNCAPPED = new Budget(null, Duration.ofMinutes(5)); + + static List commonDecision() { + return Arrays.asList( + Arguments.of("408", failed(408), Decision.RETRY), + Arguments.of("429", failed(429), Decision.RETRY), + Arguments.of("502", failed(502), Decision.RETRY), + Arguments.of("503", failed(503), Decision.RETRY), + Arguments.of("504", failed(504), Decision.RETRY), + Arguments.of("412", failed(412), Decision.RAISE), + Arguments.of("400", failed(400), Decision.WALK), + Arguments.of("403", failed(403), Decision.WALK), + Arguments.of("404", failed(404), Decision.WALK), + Arguments.of("500", failed(500), Decision.WALK), + Arguments.of( + "a 503 whose client decided to raise", + new RequestFailed(error(503), 503, Decision.RAISE), + Decision.RAISE)); + } + + @ParameterizedTest(name = "{0}") + @MethodSource + void commonDecision(String name, Exception failure, Decision want) { + assertEquals(want, FilesExtRetry.commonDecision(failure)); + } + + static List apiClientDecision() { + SourceReadFailed sourceRead = new SourceReadFailed(new IOException("disk")); + return Arrays.asList( + Arguments.of("already exists", new AlreadyExists("exists", null), Decision.RAISE), + // The classic API client's error for a 429 or 503, which has no Retry-After of its own. + Arguments.of("429 from the API client", error(429), Decision.RETRY), + Arguments.of("503 from the API client", error(503), Decision.RETRY), + // Only the common rows retry a 502; the API client's rules do not. + Arguments.of("502 from the API client", error(502), Decision.WALK), + Arguments.of("connection refused", new ConnectException("refused"), Decision.RETRY), + Arguments.of("read timeout", new SocketTimeoutException("read"), Decision.RETRY), + // As the classic API client reports an I/O failure. + Arguments.of( + "IO_ERROR from the API client", + new DatabricksError("IO_ERROR", 523, new IOException("reset")), + Decision.RETRY), + Arguments.of("body closed mid-read", new ConnectionClosedException("cut"), Decision.WALK), + Arguments.of("chunk cut mid-read", new TruncatedChunkException("cut"), Decision.WALK), + Arguments.of("source read failed", sourceRead, Decision.WALK), + // As the classic API client reports it when the read fails while it sends the body. + Arguments.of( + "source read failed, as IO_ERROR", + new DatabricksError("IO_ERROR", 523, sourceRead), + Decision.WALK), + // One message that RetryUtils matches, and one that only the extension adds. + Arguments.of( + "transient message from RetryUtils", + new DatabricksError("INTERNAL_ERROR", "failed: ClusterNotReadyException", 500), + Decision.RETRY), + Arguments.of( + "transient message from the extension", + new DatabricksError( + "INTERNAL_ERROR", "failed: RPC token bucket limit has been exceeded", 500), + Decision.RETRY), + Arguments.of("expired URL", new UrlExpired("expired"), Decision.WALK), + Arguments.of("unexpected error", new IllegalStateException("surprise"), Decision.WALK)); + } + + @ParameterizedTest(name = "{0}") + @MethodSource + void apiClientDecision(String name, Exception failure, Decision want) { + assertEquals(want, FilesExtRetry.apiClientDecision(failure)); + } + + static List retryAfterSeconds() { + return Arrays.asList( + Arguments.of( + "a recorded response's own Retry-After", + new RequestFailed(error(429), 429, null, 30L), + 30L), + // A 500 whose error class is a 503 one: the response said no Retry-After, so none. + Arguments.of( + "a recorded 500 with a 503 error class", + new RequestFailed(error(503), 500, null), + null), + // The classic API client's error for a 429 or 503 has no response to read. + Arguments.of( + "a throttled API client error", + error(503), + Long.valueOf(FilesExtRetry.DEFAULT_RETRY_AFTER_SECONDS)), + Arguments.of("an API client 404", error(404), null)); + } + + @ParameterizedTest(name = "{0}") + @MethodSource + void retryAfterSeconds(String name, Exception failure, Long want) { + assertEquals(want, FilesExtRetry.retryAfterSeconds(failure)); + } + + @Test + void retry_aFailureToReadTheSource_isNotRetried() { + Sends sends = new Sends(new SourceReadFailed(new IOException("disk"))); + + Result result = retryOnLastEndpoint(sends, UNCAPPED, new FakeClock()); + + assertEquals(Decision.WALK, result.failure.decision); + assertEquals(1, sends.count()); + } + + @Test + void unwrap_surfacesIoFailuresAsTheApiClientDoes() { + IOException cause = new IOException("reset"); + + RuntimeException error = FilesExtRetry.unwrap(cause); + + assertTrue(error instanceof DatabricksError, error.getClass().getName()); + assertEquals("IO_ERROR", ((DatabricksError) error).getErrorCode()); + assertEquals(523, ((DatabricksError) error).getStatusCode()); + assertSame(cause, error.getCause()); + } + + @Test + void unwrap_surfacesTheErrorOfARequestFailed() { + DatabricksError error = error(503); + + assertSame(error, FilesExtRetry.unwrap(new RequestFailed(error, 503, null))); + } + + @Test + void retry_returnsTheFirstSuccess() { + FakeClock clock = new FakeClock(); + Sends sends = new Sends(failed(503), failed(503)); + + Result result = retryOnLastEndpoint(sends, UNCAPPED, clock); + + assertEquals("ok", result.value); + assertFalse(result.failed()); + assertEquals(3, sends.count()); + } + + @Test + void retry_backsOffMinOfTenAndTheAttemptPlusJitter() { + FakeClock clock = new FakeClock(); + Exception[] failures = new Exception[12]; + Arrays.fill(failures, failed(502)); + + retryOnLastEndpoint(new Sends(failures), UNCAPPED, clock); + + List waits = clock.waits(); + assertEquals(12, waits.size(), waits.toString()); + for (int i = 0; i < waits.size(); i++) { + long base = Math.min(10, i + 1) * 1000L; + assertTrue(waits.get(i) >= base && waits.get(i) < base + 1000, i + ": " + waits); + } + } + + @Test + void retry_a503WithoutRetryAfterFromItsClient_backsOff() { + // A cloud request's 503: its client read no Retry-After, so the wait is the backoff, not the + // API client's 1 s default. + FakeClock clock = new FakeClock(); + retryOnLastEndpoint(new Sends(failed(503), failed(503), failed(503)), UNCAPPED, clock); + + List waits = clock.waits(); + assertEquals(3, waits.size(), waits.toString()); + for (int i = 0; i < waits.size(); i++) { + long base = (i + 1) * 1000L; + assertTrue(waits.get(i) >= base && waits.get(i) < base + 1000, i + ": " + waits); + } + assertNull(FilesExtRetry.retryAfterSeconds(failed(503))); + } + + @Test + void retry_waitsRetryAfter() { + FakeClock clock = new FakeClock(); + Sends sends = new Sends(new RequestFailed(error(429), 429, null, 7L)); + + retryOnLastEndpoint(sends, UNCAPPED, clock); + + long wait = clock.waits().get(0); + assertTrue(wait >= 7000 && wait < 8000, String.valueOf(wait)); + } + + @ParameterizedTest + @ValueSource(longs = {60, Long.MAX_VALUE}) + void retry_aRetryAfterPastTheBudget_failsAtOnceWithoutWaiting(long retryAfter) { + FakeClock clock = new FakeClock(); + Sends sends = new Sends(new RequestFailed(error(429), 429, null, retryAfter)); + + Result result = + retryOnLastEndpoint(sends, new Budget(null, Duration.ofSeconds(10)), clock); + + assertEquals(Decision.WALK, result.failure.decision); + assertEquals("Timed out after PT10S", result.failure.error.getMessage()); + assertEquals(1, sends.count()); + assertEquals(Collections.emptyList(), clock.sleeps); + } + + @Test + void retry_aNegativeRetryAfter_waitsOnlyTheJitter() { + FakeClock clock = new FakeClock(); + Sends sends = new Sends(new RequestFailed(error(429), 429, null, -5L)); + + retryOnLastEndpoint(sends, UNCAPPED, clock); + + long wait = clock.waits().get(0); + assertTrue(wait >= 0 && wait < 1000, String.valueOf(wait)); + assertEquals(2, sends.count()); + long computed = FilesExtRetry.waitMillis(-5L, 1); + assertTrue(computed >= 0 && computed < 1000, String.valueOf(computed)); + } + + @Test + void waitMillis_ofAHugeRetryAfter_saturatesInsteadOfOverflowing() { + long wait = FilesExtRetry.waitMillis(Long.MAX_VALUE, 1); + + assertTrue(wait > Long.MAX_VALUE - 2000, String.valueOf(wait)); + } + + @Test + void retry_sleepsInStepsOfAtMostASecond() { + FakeClock clock = new FakeClock(); + + retryOnLastEndpoint(new Sends(new RequestFailed(error(429), 429, null, 3L)), UNCAPPED, clock); + + for (long step : clock.sleeps) { + assertTrue(step <= 1000, clock.sleeps.toString()); + } + } + + @Test + void retry_stopsAtWalkOrRaiseWithoutWaiting() { + FakeClock clock = new FakeClock(); + DatabricksError notFound = error(404); + + Result walked = retryOnLastEndpoint(new Sends(notFound), UNCAPPED, clock); + Result raised = retryOnLastEndpoint(new Sends(failed(412)), UNCAPPED, clock); + + assertEquals(Decision.WALK, walked.failure.decision); + assertSame(notFound, walked.failure.error); + assertEquals(Decision.RAISE, raised.failure.decision); + assertEquals(Collections.emptyList(), clock.waits()); + } + + @Test + void retry_beforeCommitWithAnotherEndpoint_retriesOnlyRetriesBeforeCommitTimes() { + FakeClock clock = new FakeClock(); + Sends sends = new Sends(failed(503), failed(503), failed(503)); + + Result result = + FilesExtRetry.retry( + sends, FilesExtRetry::commonDecision, UNCAPPED, new TransferStatus(false, 1), clock); + + assertEquals(Decision.WALK, result.failure.decision); + assertEquals(2, sends.count()); + } + + @Test + void retry_afterCommit_retriesEvenWithAnotherEndpoint() { + FakeClock clock = new FakeClock(); + Sends sends = new Sends(failed(503), failed(503)); + TransferStatus status = new TransferStatus(false, 0); + status.commit(); + + Result result = + FilesExtRetry.retry(sends, FilesExtRetry::commonDecision, UNCAPPED, status, clock); + + assertEquals("ok", result.value); + assertEquals(3, sends.count()); + } + + @Test + void retry_exceedingMaxAttempts_walksWithTheExhaustedError() { + FakeClock clock = new FakeClock(); + Exception[] failures = new Exception[5]; + Arrays.fill(failures, failed(503)); + Sends sends = new Sends(failures); + + Result result = retryOnLastEndpoint(sends, new Budget(3, Duration.ofMinutes(5)), clock); + + assertEquals(3, sends.count()); + assertEquals(Decision.WALK, result.failure.decision); + assertEquals(DatabricksException.class, result.failure.error.getClass()); + assertEquals("Exceeded max retry attempts (3)", result.failure.error.getMessage()); + assertTrue(result.failure.error.getCause() instanceof DatabricksError); + // No wait after the last attempt. + assertEquals(2, clock.waits().size()); + } + + @Test + void retry_runningOutOfTime_walksWithTheTimeoutError() { + FakeClock clock = new FakeClock(); + Exception[] failures = new Exception[100]; + Arrays.fill(failures, failed(503)); + Sends sends = new Sends(failures); + + Result result = + retryOnLastEndpoint(sends, new Budget(null, Duration.ofSeconds(10)), clock); + + assertEquals(DatabricksException.class, result.failure.error.getClass()); + assertEquals("Timed out after PT10S", result.failure.error.getMessage()); + assertTrue(result.failure.error.getCause() instanceof DatabricksError); + // It stops before a wait that would end past the budget, rather than sleeping into it. + assertTrue(clock.now < 10_000, String.valueOf(clock.now)); + } + + @Test + void retry_whenTheRequestCannotBeSentAgain_walks() { + FakeClock clock = new FakeClock(); + Sends sends = new Sends(failed(503)); + + Result result = + FilesExtRetry.retry( + sends, + FilesExtRetry::commonDecision, + UNCAPPED, + new TransferStatus(true, 0), + clock, + null, + () -> false); + + assertEquals(Decision.WALK, result.failure.decision); + assertEquals(1, sends.count()); + } + + @Test + void retry_runsBeforeRetryBeforeEachWait() { + FakeClock clock = new FakeClock(); + AtomicInteger beforeRetries = new AtomicInteger(); + + FilesExtRetry.retry( + new Sends(failed(503), failed(503)), + FilesExtRetry::commonDecision, + UNCAPPED, + new TransferStatus(true, 0), + clock, + beforeRetries::incrementAndGet, + null); + + assertEquals(2, beforeRetries.get()); + } + + @Test + void retry_cancelledDuringTheWait_wakesEarlyAndWalks() { + TransferStatus status = new TransferStatus(true, 0); + FakeClock clock = new FakeClock(); + clock.onSleep = status::cancel; + Sends sends = new Sends(new RequestFailed(error(429), 429, null, 30L)); + + Result result = + FilesExtRetry.retry(sends, FilesExtRetry::commonDecision, UNCAPPED, status, clock); + + assertEquals(Decision.WALK, result.failure.decision); + assertEquals(1, clock.sleeps.size(), clock.sleeps.toString()); + assertEquals(1, sends.count()); + } + + @Test + void retry_cancelled_doesNotRetry() { + TransferStatus status = new TransferStatus(true, 0); + status.cancel(); + Sends sends = new Sends(failed(503)); + + Result result = + FilesExtRetry.retry( + sends, FilesExtRetry::commonDecision, UNCAPPED, status, new FakeClock()); + + assertEquals(Decision.WALK, result.failure.decision); + assertEquals(1, sends.count()); + } + + @Test + void retry_interruptedWhileWaiting_throwsAsTheApiClientDoes() { + Timer interrupting = + new Timer() { + @Override + public void sleep(long milliseconds) throws InterruptedException { + throw new InterruptedException(); + } + + @Override + public long getCurrentTime() { + return 0; + } + }; + + try { + DatabricksException e = + assertThrows( + DatabricksException.class, + () -> retryOnLastEndpoint(new Sends(failed(503)), UNCAPPED, interrupting)); + + assertEquals("Current thread was interrupted", e.getMessage()); + assertTrue(Thread.currentThread().isInterrupted()); + } finally { + Thread.interrupted(); + } + } + + @ParameterizedTest + @ValueSource(ints = {503, 404}) + void retry_failureWhileInterrupted_throwsWithoutRetryingOrWalking(int status) { + RequestFailed failure = failed(status); + Sends sends = new Sends(failure); + Thread.currentThread().interrupt(); + try { + DatabricksException e = + assertThrows( + DatabricksException.class, + () -> retryOnLastEndpoint(sends, UNCAPPED, new FakeClock())); + + assertEquals("Current thread was interrupted", e.getMessage()); + assertSame(failure.error, e.getCause()); + assertEquals(1, sends.count()); + assertTrue(Thread.currentThread().isInterrupted()); + } finally { + Thread.interrupted(); + } + } + + @Test + void walkEndpoints_walksToTheNextEndpointBeforeCommit() { + List tried = new ArrayList<>(); + AtomicInteger beforeNext = new AtomicInteger(); + + FilesExtRetry.walkEndpoints( + clients("offload", "workspace"), + (client, status) -> { + tried.add(client.name() + (status.isLastEndpoint ? " last" : "")); + return client.name().equals("offload") ? walk() : null; + }, + () -> true, + beforeNext::incrementAndGet, + 2); + + assertEquals(Arrays.asList("offload", "workspace last"), tried); + assertEquals(1, beforeNext.get()); + } + + @Test + void walkEndpoints_givesEachEndpointANewStatus() { + List statuses = new ArrayList<>(); + + FilesExtRetry.walkEndpoints( + clients("a", "b"), + (client, status) -> { + statuses.add(status); + return statuses.size() == 1 ? walk() : null; + }, + () -> true, + () -> {}, + 3); + + assertEquals(2, statuses.size()); + assertFalse(statuses.get(0) == statuses.get(1)); + assertEquals(3, statuses.get(1).retriesBeforeCommit); + } + + @Test + void walkEndpoints_raisesWithoutWalking() { + List tried = new ArrayList<>(); + DatabricksError error = error(412); + + DatabricksError thrown = + assertThrows( + DatabricksError.class, + () -> + FilesExtRetry.walkEndpoints( + clients("a", "b"), + (client, status) -> { + tried.add(client.name()); + return new Failure(error, Decision.RAISE); + })); + + assertSame(error, thrown); + assertEquals(Collections.singletonList("a"), tried); + } + + @Test + void walkEndpoints_afterCommit_doesNotWalk() { + List tried = new ArrayList<>(); + + assertThrows( + DatabricksError.class, + () -> + FilesExtRetry.walkEndpoints( + clients("a", "b"), + (client, status) -> { + tried.add(client.name()); + status.commit(); + return walk(); + })); + + assertEquals(Collections.singletonList("a"), tried); + } + + @Test + void walkEndpoints_whenTheDataCannotBeSentAgain_doesNotWalk() { + List tried = new ArrayList<>(); + + assertThrows( + DatabricksError.class, + () -> + FilesExtRetry.walkEndpoints( + clients("a", "b"), + (client, status) -> { + tried.add(client.name()); + return walk(); + }, + () -> false, + () -> {}, + 0)); + + assertEquals(Collections.singletonList("a"), tried); + } + + @Test + void walkEndpoints_throwsTheLastEndpointsError() { + DatabricksError last = error(500); + + DatabricksError thrown = + assertThrows( + DatabricksError.class, + () -> + FilesExtRetry.walkEndpoints( + clients("a", "b"), + (client, status) -> + new Failure(client.name().equals("b") ? last : error(404), Decision.WALK))); + + assertSame(last, thrown); + } + + @Test + void walkEndpoints_withoutEndpoints_throws() { + assertThrows( + IllegalArgumentException.class, + () -> FilesExtRetry.walkEndpoints(clients(), (client, status) -> null)); + } + + @Test + void mayWalk_onlyAWalkBeforeCommitWithAnotherEndpointAndDataToSend() { + TransferStatus status = new TransferStatus(false, 0); + Failure walk = walk(); + + assertTrue(FilesExtRetry.mayWalk(walk, status, true, () -> true)); + assertFalse( + FilesExtRetry.mayWalk(new Failure(error(412), Decision.RAISE), status, true, () -> true)); + assertFalse(FilesExtRetry.mayWalk(walk, status, false, () -> true)); + assertFalse(FilesExtRetry.mayWalk(walk, status, true, () -> false)); + status.commit(); + assertFalse(FilesExtRetry.mayWalk(walk, status, true, () -> true)); + } + + @Test + void retry_outOfTimeOnTheLastAllowedAttempt_isATimeout() { + FakeClock clock = new FakeClock(); + Exception[] failures = new Exception[10]; + Arrays.fill(failures, failed(502)); + Sends sends = new Sends(failures); + + // Waits of 1, 2, 3 and 4 seconds use up the 10 seconds just as the fifth attempt is due. + Result result = + retryOnLastEndpoint(sends, new Budget(5, Duration.ofSeconds(10)), clock); + + assertEquals(4, sends.count()); + assertEquals("Timed out after PT10S", result.failure.error.getMessage()); + } + + @Test + void exhaustedError_keepsTheLastFailureAsItsCause() { + DatabricksError last = error(503); + + assertSame( + last, + FilesExtRetry.exhaustedError(new Budget(2, Duration.ofSeconds(1)), 3, last).getCause()); + assertNull(FilesExtRetry.exhaustedError(UNCAPPED, 1, null).getCause()); + } + + private static Result retryOnLastEndpoint(Send send, Budget budget, Timer clock) { + Runnable beforeRetry = clock instanceof FakeClock ? ((FakeClock) clock)::newWait : null; + return FilesExtRetry.retry( + send, + FilesExtRetry::commonDecision, + budget, + new TransferStatus(true, 0), + clock, + beforeRetry, + null); + } + + private static Failure walk() { + return new Failure(error(503), Decision.WALK); + } + + private static DatabricksError error(int status) { + return new DatabricksError("ERROR_" + status, "status " + status, status); + } + + private static RequestFailed failed(int status) { + return new RequestFailed(error(status), status, null); + } + + private static List clients(String... names) { + List clients = new ArrayList<>(); + for (String name : names) { + clients.add(() -> name); + } + return clients; + } + + /** Fails with the given exceptions in order, then returns "ok". */ + private static final class Sends implements Send { + private final List failures; + private int count; + + Sends(Exception... failures) { + this.failures = new ArrayList<>(Arrays.asList(failures)); + } + + @Override + public String send() throws Exception { + count++; + if (!failures.isEmpty()) { + throw failures.remove(0); + } + return "ok"; + } + + int count() { + return count; + } + } + + /** A clock that advances on sleep and records each sleep, grouped into waits. */ + private static final class FakeClock implements Timer { + long now; + final List sleeps = new ArrayList<>(); + private final List waits = new ArrayList<>(); + Runnable onSleep = () -> {}; + + /** Starts a new wait; the loop calls it, through beforeRetry, before each one. */ + void newWait() { + waits.add(0L); + } + + @Override + public void sleep(long milliseconds) { + sleeps.add(milliseconds); + if (!waits.isEmpty()) { + waits.set(waits.size() - 1, waits.get(waits.size() - 1) + milliseconds); + } + now += milliseconds; + onSleep.run(); + } + + @Override + public long getCurrentTime() { + return now; + } + + List waits() { + return new ArrayList<>(waits); + } + } +} diff --git a/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtTest.java b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtTest.java new file mode 100644 index 000000000..4f35000eb --- /dev/null +++ b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtTest.java @@ -0,0 +1,342 @@ +package com.databricks.sdk.mixin; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import com.databricks.sdk.WorkspaceClient; +import com.databricks.sdk.core.ApiClient; +import com.databricks.sdk.core.DatabricksConfig; +import com.databricks.sdk.core.DatabricksError; +import com.databricks.sdk.core.DummyCredentialsProvider; +import com.databricks.sdk.core.http.HttpClient; +import com.databricks.sdk.core.http.Request; +import com.databricks.sdk.core.http.Response; +import com.databricks.sdk.core.logging.ILoggerFactory; +import com.databricks.sdk.core.logging.Logger; +import com.databricks.sdk.core.logging.LoggerFactory; +import com.databricks.sdk.core.logging.Slf4jLoggerFactory; +import com.databricks.sdk.core.utils.FakeTimer; +import com.databricks.sdk.service.files.DownloadRequest; +import com.databricks.sdk.service.files.FilesAPI; +import com.databricks.sdk.service.files.FilesService; +import com.databricks.sdk.service.files.UploadRequest; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Deque; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * How a {@link FilesExt} is built decides whether it has the transfer extension, and with it the + * single-attempt workspace client. The user's own client and config keep their retries either way. + */ +public class FilesExtTest { + private static final String HOST = "http://localhost"; + private static final String FILE = "/Volumes/catalog/schema/volume/file.bin"; + private static final String FILES_PATH = "/api/2.0/fs/files" + FILE; + + @Test + void builtWithTheConfig_sendsExtensionCallsOnce() { + FakeServer server = new FakeServer(); + DatabricksConfig config = config(server); + // What new WorkspaceClient(config) does, retries on as the user configured them. + ApiClient apiClient = new ApiClient(config); + int metadataFetches = server.metadataFetches(); + + FilesExt files = new FilesExt(apiClient, config); + server.answers(503, 200); + + assertTrue(files.hasTransferExtension()); + // Building it does not resolve the config again, which would fetch host metadata again. + assertEquals(metadataFetches, server.metadataFetches()); + assertThrows( + DatabricksError.class, + () -> files.singleAttemptApiClient().execute(new Request("GET", FILES_PATH), Void.class)); + assertEquals(1, server.fileRequests()); + // The user's config still retries. + assertFalse(config.getDisableRetries()); + } + + @Test + void builtWithTheConfig_leavesTheUsersClientRetrying() throws IOException { + FakeServer server = new FakeServer(); + DatabricksConfig config = config(server); + ApiClient userClient = new ApiClient(config, new FakeTimer()); + new FilesExt(userClient, config); + server.answers(503, 200); + + userClient.execute(new Request("GET", FILES_PATH), Void.class); + + assertEquals(2, server.fileRequests()); + } + + @Test + void builtFromACustomApiClient_keepsTheGeneratedPathAndItsRetries() throws IOException { + FakeServer server = new FakeServer(); + // A custom client, here with its own timer, which a FilesExt cannot copy without its retries. + ApiClient custom = new ApiClient(config(server), new FakeTimer()); + FilesExt files = new FilesExt(custom); + server.answers(503, 200); + + files.download(new DownloadRequest().setFilePath(FILE)).getContents().close(); + + assertFalse(files.hasTransferExtension()); + // The generated download, retried once by the custom client's own retries. + assertEquals(Collections.nCopies(2, "GET " + FILES_PATH), server.fileRequestLog()); + } + + @Test + void builtOverAMock_callsTheMockAsBefore() { + FilesService service = mock(FilesService.class); + UploadRequest request = + new UploadRequest().setFilePath(FILE).setContents(new ByteArrayInputStream(new byte[3])); + + FilesExt direct = new FilesExt(service); + direct.upload(request); + FilesExt.of(new WorkspaceClient(true).withFilesImpl(service)).upload(request); + + assertFalse(direct.hasTransferExtension()); + verify(service, times(2)).upload(request); + } + + @Test + void of_returnsTheFilesExtOfTheWorkspaceClient() { + FilesExt files = new FilesExt(mock(FilesService.class)); + + assertSame(files, FilesExt.of(new WorkspaceClient(true).withFilesAPI(files))); + } + + static List of_rejects() { + return Arrays.asList( + Arguments.of( + "a FilesAPI without a FilesService", + (Supplier) + () -> new WorkspaceClient(true).withFilesAPI(mock(FilesAPI.class)), + "workspaceClient.files() has no FilesService; tests that call FilesExt.of(w) should" + + " inject mock(FilesExt.class) with withFilesAPI"), + Arguments.of( + // WorkspaceClient(mock, apiClient) builds no services. + "a WorkspaceClient without files", + (Supplier) + () -> new WorkspaceClient(true, new ApiClient(config(new FakeServer()))), + "workspaceClient.files() is not set; set it with withFilesAPI or withFilesImpl")); + } + + @ParameterizedTest(name = "{0}") + @MethodSource + void of_rejects(String name, Supplier workspaceClient, String message) { + WorkspaceClient w = workspaceClient.get(); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> FilesExt.of(w)); + + assertEquals(message, e.getMessage()); + } + + @Test + void builtWithAnotherConfig_hasNoExtensionAndWarns() { + ApiClient apiClient = new ApiClient(config(new FakeServer())); + DatabricksConfig other = config(new FakeServer()); + + List warnings = + captureWarnings(() -> assertFalse(new FilesExt(apiClient, other).hasTransferExtension())); + + assertEquals( + Collections.singletonList( + "The Files transfer extension is off, using the generated upload and download: the" + + " config is not the one the API client was built from: they have different HTTP" + + " clients"), + warnings); + } + + @Test + void builtWhenTheSingleAttemptClientCannotBeBuilt_hasNoExtensionAndWarns() { + DatabricksConfig config = new FailsForFilesExtConfig(); + config + .setHost(HOST) + .setCredentialsProvider(new DummyCredentialsProvider()) + .setHttpClient(new FakeServer()); + ApiClient apiClient = new ApiClient(config); + + List warnings = + captureWarnings(() -> assertFalse(new FilesExt(apiClient, config).hasTransferExtension())); + + assertEquals( + Collections.singletonList( + "The Files transfer extension is off, using the generated upload and download: its" + + " single-attempt API client could not be built: java.lang.IllegalStateException:" + + " simulated failure building the single-attempt client"), + warnings); + } + + /** A config that fails only when FilesExt builds its single-attempt client from it. */ + static final class FailsForFilesExtConfig extends DatabricksConfig { + @Override + public Integer getDebugTruncateBytes() { + for (StackTraceElement frame : new Throwable().getStackTrace()) { + if (frame.getClassName().equals(FilesExt.class.getName())) { + throw new IllegalStateException("simulated failure building the single-attempt client"); + } + } + return super.getDebugTruncateBytes(); + } + } + + /** Runs {@code body} with a logger factory that records warnings, and returns them. */ + private static List captureWarnings(Runnable body) { + List warnings = Collections.synchronizedList(new ArrayList()); + LoggerFactory.setDefault(new CapturingLoggerFactory(warnings)); + try { + body.run(); + } finally { + LoggerFactory.setDefault(Slf4jLoggerFactory.INSTANCE); + } + return new ArrayList<>(warnings); + } + + private static final class CapturingLoggerFactory implements ILoggerFactory { + private final List warnings; + + CapturingLoggerFactory(List warnings) { + this.warnings = warnings; + } + + @Override + public Logger getLogger(Class type) { + return getLogger(type.getName()); + } + + @Override + public Logger getLogger(String name) { + return new Logger() { + @Override + public void debug(String msg) {} + + @Override + public void debug(String format, Object... args) {} + + @Override + public void debug(Supplier msgSupplier) {} + + @Override + public void info(String msg) {} + + @Override + public void info(String format, Object... args) {} + + @Override + public void info(Supplier msgSupplier) {} + + @Override + public void warn(String msg) { + warnings.add(msg); + } + + @Override + public void warn(String format, Object... args) { + // Each {} takes the next argument, as SLF4J formats it. + StringBuilder message = new StringBuilder(); + int from = 0; + for (Object arg : args) { + int at = format.indexOf("{}", from); + if (at < 0) { + break; + } + message.append(format, from, at).append(arg); + from = at + 2; + } + warnings.add(message.append(format.substring(from)).toString()); + } + + @Override + public void warn(Supplier msgSupplier) { + warnings.add(msgSupplier.get()); + } + + @Override + public void error(String msg) {} + + @Override + public void error(String format, Object... args) {} + + @Override + public void error(Supplier msgSupplier) {} + }; + } + } + + private static DatabricksConfig config(HttpClient httpClient) { + return new DatabricksConfig() + .setHost(HOST) + .setCredentialsProvider(new DummyCredentialsProvider()) + .setHttpClient(httpClient); + } + + /** + * Answers the Files API with queued statuses (200 once the queue is empty) and the host-metadata + * request with 404, recording every request. + */ + private static final class FakeServer implements HttpClient { + private final Deque statuses = new ArrayDeque<>(); + private final List log = Collections.synchronizedList(new ArrayList()); + + void answers(Integer... queued) { + Collections.addAll(statuses, queued); + } + + int metadataFetches() { + return Collections.frequency(log, "GET /.well-known/databricks-config"); + } + + List fileRequestLog() { + List files = new ArrayList<>(); + synchronized (log) { + for (String r : log) { + if (r.contains("/api/2.0/fs/files")) { + files.add(r); + } + } + } + return files; + } + + int fileRequests() { + return fileRequestLog().size(); + } + + @Override + public Response execute(Request in) throws IOException { + String path = in.getUri().getPath(); + log.add(in.getMethod() + " " + path); + Integer status = + path.startsWith("/api/2.0/fs/files") ? statuses.poll() : Integer.valueOf(404); + int code = status == null ? 200 : status; + String body = + code == 200 ? "" : "{\"error_code\": \"TEMPORARILY_UNAVAILABLE\", \"message\": \"no\"}"; + Map> headers = + Collections.singletonMap("Content-Type", Collections.singletonList("application/json")); + return new Response( + in, + in.getUri().toURL(), + code, + "status " + code, + headers, + new ByteArrayInputStream(body.getBytes(UTF_8))); + } + } +} diff --git a/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtTests.java b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtTests.java new file mode 100644 index 000000000..444098773 --- /dev/null +++ b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtTests.java @@ -0,0 +1,76 @@ +package com.databricks.sdk.mixin; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.Enumeration; +import java.util.Set; +import java.util.TreeSet; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; + +/** + * Runs every test class of the Files transfer extension and its transfer contract test in the one + * Bazel target {@code :files_ext_tests}. The Bazel JUnit runner runs a target's test class and that + * class's static nested classes, and JUnit runs the tests a class inherits. Each nested class here + * extends one test class, so a new test class needs a line here and no BUILD change. + */ +final class FilesExtTests { + private static final Pattern TEST_CLASS = + Pattern.compile("com/databricks/sdk/mixin/(FilesExt\\w*Test)\\.class"); + + static final class Endpoints extends FilesExtEndpointsTest {} + + static final class Mixin extends FilesExtTest {} + + static final class Retry extends FilesExtRetryTest {} + + static final class ResponseRecorder extends FilesExtResponseRecorderTest {} + + static final class UploadData extends FilesExtUploadDataTest {} + + static final class UploadPlan extends FilesExtUploadPlanTest {} + + static final class UploadWalk extends FilesExtUploadWalkTest {} + + static final class EndpointClients extends FilesExtEndpointClientsTest {} + + static final class Presigned extends FilesExtPresignedTest {} + + static final class FakeServer extends FilesExtFakeServerTest {} + + static final class Contract extends FilesExtContractTest {} + + /** A test class without a nested class here would compile into the target and never run. */ + @Test + void everyTestClassOfTheTargetRuns() throws IOException, URISyntaxException { + // Only Bazel (which sets TEST_SRCDIR) runs the test classes through this one; the public Maven + // build runs each test class itself, from a directory rather than a jar. + Assumptions.assumeTrue(System.getenv("TEST_SRCDIR") != null, "not run under Bazel"); + File jar = + new File(FilesExtTests.class.getProtectionDomain().getCodeSource().getLocation().toURI()); + assertTrue(jar.isFile(), "not run from the target's jar: " + jar); + Set compiled = new TreeSet<>(); + try (JarFile file = new JarFile(jar)) { + for (Enumeration entries = file.entries(); entries.hasMoreElements(); ) { + Matcher m = TEST_CLASS.matcher(entries.nextElement().getName()); + if (m.matches()) { + compiled.add(m.group(1)); + } + } + } + Set run = new TreeSet<>(); + for (Class nested : FilesExtTests.class.getDeclaredClasses()) { + run.add(nested.getSuperclass().getSimpleName()); + } + + assertEquals(compiled, run); + } +} diff --git a/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtUploadDataTest.java b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtUploadDataTest.java new file mode 100644 index 000000000..78652b135 --- /dev/null +++ b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtUploadDataTest.java @@ -0,0 +1,668 @@ +package com.databricks.sdk.mixin; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.databricks.sdk.mixin.FilesExtRetry.SourceReadFailed; +import com.databricks.sdk.mixin.FilesExtUploadData.Part; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.channels.ClosedByInterruptException; +import java.nio.channels.FileChannel; +import java.nio.channels.SeekableByteChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Random; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +/** The upload data of each source kind. */ +public class FilesExtUploadDataTest { + private static final byte[] CONTENT = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + + @TempDir Path tempDir; + + private final List opened = new ArrayList<>(); + + @AfterEach + void closeOpened() throws Exception { + for (AutoCloseable c : opened) { + c.close(); + } + } + + @ParameterizedTest + @CsvSource({ + "file, 0", "file, 3", "file, 4", "file, 10", + "channel, 0", "channel, 3", "channel, 4", "channel, 10", + "one-pass, 0", "one-pass, 3", "one-pass, 4", "one-pass, 10", + "short-reads, 0", "short-reads, 3", "short-reads, 4", "short-reads, 10" + }) + void partsCoverTheDataInOrder(String source, int length) throws IOException { + byte[] content = Arrays.copyOf(CONTENT, length); + FilesExtUploadData data = data(source, content); + + List parts = allParts(data, 4); + + for (int i = 0; i < parts.size(); i++) { + assertEquals(i + 1, parts.get(i).number); + if (i < parts.size() - 1) { + assertEquals(4, parts.get(i).data.length); + } + } + assertArrayEquals(content, join(parts)); + assertEquals(Long.valueOf(length), data.sizeOrNull()); + } + + @ParameterizedTest + @ValueSource(strings = {"file", "channel", "one-pass", "short-reads"}) + void sizeIsKnownUpFrontOnlyWhenRewindable(String source) throws IOException { + FilesExtUploadData data = data(source, CONTENT); + + assertEquals(rewindable(source) ? Long.valueOf(CONTENT.length) : null, data.sizeOrNull()); + } + + @ParameterizedTest + @CsvSource({ + "file, 5, ", "file, 10, ", "file, 11, ", + "channel, 5, ", "channel, 10, ", "channel, 11, ", + "one-pass, 5, ", "one-pass, 10, ", "one-pass, 11, 10", + "short-reads, 5, ", "short-reads, 10, ", "short-reads, 11, 10" + }) + void readAheadLearnsTheSizeOfAShortStreamWithoutConsuming(String source, int ahead, Long size) + throws IOException { + FilesExtUploadData data = data(source, CONTENT); + + data.readAhead(ahead); + + assertEquals(rewindable(source) ? Long.valueOf(CONTENT.length) : size, data.sizeOrNull()); + assertParts(allParts(data, 4), new int[] {1, 2, 3}, 0, 4, 8, 10); + } + + @ParameterizedTest + @ValueSource(strings = {"one-pass", "short-reads"}) + void readAheadOfAnEmptyStreamLearnsSizeZero(String source) throws IOException { + FilesExtUploadData data = data(source, new byte[0]); + + data.readAhead(4); + + assertEquals(Long.valueOf(0), data.sizeOrNull()); + assertNull(data.nextPart(4)); + } + + @ParameterizedTest + @ValueSource(strings = {"file", "channel", "one-pass", "short-reads"}) + void restartsFromTheStartBeforeCommit(String source) throws IOException { + FilesExtUploadData data = data(source, CONTENT); + assertArrayEquals(Arrays.copyOf(CONTENT, 4), data.nextPart(4).data); + + assertTrue(data.canSendAgain()); + data.restart(); + + assertParts(allParts(data, 4), new int[] {1, 2, 3}, 0, 4, 8, 10); + } + + @ParameterizedTest + @ValueSource(strings = {"file", "channel", "one-pass", "short-reads"}) + void afterCommit_continuesAndOnlyRewindableDataCanBeSentAgain(String source) throws IOException { + FilesExtUploadData data = data(source, CONTENT); + data.nextPart(4); + + data.dropReplayBuffer(); + + assertParts(allParts(data, 4), new int[] {2, 3}, 4, 8, 10); + assertEquals(rewindable(source), data.canSendAgain()); + } + + @ParameterizedTest + @ValueSource(strings = {"one-pass", "short-reads"}) + void onePassData_keepsNoBytesAfterCommit(String source) throws IOException { + FilesExtUploadData data = data(source, new byte[1000]); + data.nextPart(100); + + data.dropReplayBuffer(); + allParts(data, 100); + + assertEquals(0, data.keptBytes()); + assertFalse(data.canSendAgain()); + // Nothing kept: what was read after commit is not replayed. + data.restart(); + assertNull(data.nextPart(100)); + } + + @ParameterizedTest + @ValueSource(strings = {"one-pass", "short-reads"}) + void onePassData_committedBeforeAnyRead_cannotBeSentAgainOnceRead(String source) + throws IOException { + FilesExtUploadData data = data(source, CONTENT); + data.dropReplayBuffer(); + + data.nextPart(4); + + // The bytes handed out were not kept, though the replay still starts at the first byte. + assertFalse(data.canSendAgain()); + } + + @ParameterizedTest + @CsvSource({ + "file, 0", "file, 4", "file, 11", + "channel, 0", "channel, 4", "channel, 11", + "one-pass, 0", "one-pass, 4", "one-pass, 11", + "short-reads, 0", "short-reads, 4", "short-reads, 11" + }) + void wholeIsTheDataFromTheStart(String source, int ahead) throws IOException { + FilesExtUploadData data = data(source, CONTENT); + data.readAhead(ahead); + + assertArrayEquals(CONTENT, readToEnd(data.whole())); + // A one-pass stream read whole ahead is sent from memory; otherwise its rest is streamed once. + assertEquals(rewindable(source) || ahead > CONTENT.length, data.canSendAgain()); + } + + @ParameterizedTest + @ValueSource(strings = {"file", "channel", "one-pass", "short-reads"}) + void wholeAfterAPartIsTheDataFromTheStart(String source) throws IOException { + FilesExtUploadData data = data(source, CONTENT); + data.nextPart(4); + data.restart(); + + assertArrayEquals(CONTENT, readToEnd(data.whole())); + } + + @ParameterizedTest + @ValueSource(strings = {"file", "channel"}) + void wholeOfARewindableSource_canBeSentAgain(String source) throws IOException { + FilesExtUploadData data = data(source, CONTENT); + readToEnd(data.whole()); + + assertTrue(data.canSendAgain()); + assertArrayEquals(CONTENT, readToEnd(data.whole())); + } + + @ParameterizedTest + @ValueSource(strings = {"file", "channel", "one-pass", "short-reads"}) + void handsEachPartToOneThread(String source) throws Exception { + byte[] content = new byte[10_000]; + new Random(7).nextBytes(content); + FilesExtUploadData data = data(source, content); + List parts = Collections.synchronizedList(new ArrayList<>()); + List errors = Collections.synchronizedList(new ArrayList<>()); + List threads = new ArrayList<>(); + for (int i = 0; i < 8; i++) { + threads.add( + new Thread( + () -> { + try { + for (Part p = data.nextPart(7); p != null; p = data.nextPart(7)) { + parts.add(p); + } + } catch (Throwable t) { + errors.add(t); + } + })); + } + for (Thread t : threads) { + t.start(); + } + for (Thread t : threads) { + t.join(); + } + + assertEquals(Collections.emptyList(), errors); + List sorted = new ArrayList<>(parts); + sorted.sort(Comparator.comparingInt(p -> p.number)); + for (int i = 0; i < sorted.size(); i++) { + assertEquals(i + 1, sorted.get(i).number); + } + assertArrayEquals(content, join(sorted)); + } + + @Test + void channel_isUploadedFromItsPosition() throws IOException { + SeekableByteChannel channel = channel(CONTENT); + channel.position(3); + FilesExtUploadData data = FilesExtUploadData.fromChannel(channel); + + assertEquals(Long.valueOf(7), data.sizeOrNull()); + assertArrayEquals(Arrays.copyOfRange(CONTENT, 3, 10), readToEnd(data.whole())); + data.restart(); + assertArrayEquals(Arrays.copyOfRange(CONTENT, 3, 7), data.nextPart(4).data); + } + + @Test + void closesOnlyTheFileItOpened() throws IOException { + Path path = Files.write(tempDir.resolve("source"), CONTENT); + FilesExtUploadData fromFile = FilesExtUploadData.fromFile(path); + fromFile.nextPart(4); + SeekableByteChannel channel = channel(CONTENT); + FilesExtUploadData fromChannel = FilesExtUploadData.fromChannel(channel); + ClosingStream stream = new ClosingStream(new ByteArrayInputStream(CONTENT)); + FilesExtUploadData fromStream = FilesExtUploadData.fromStream(stream); + readToEnd(fromChannel.whole()); + readToEnd(fromStream.whole()); + + fromFile.close(); + fromChannel.close(); + fromStream.close(); + + // The file is reopened, from the start, if read again. + fromFile.restart(); + assertArrayEquals(Arrays.copyOf(CONTENT, 4), fromFile.nextPart(4).data); + fromFile.close(); + assertTrue(channel.isOpen()); + assertFalse(stream.closed); + } + + @Test + void closingWhole_leavesTheSourceOpen() throws IOException { + SeekableByteChannel channel = channel(CONTENT); + FilesExtUploadData data = FilesExtUploadData.fromChannel(channel); + + data.whole().close(); + + assertTrue(channel.isOpen()); + } + + @ParameterizedTest + @ValueSource(strings = {"read", "whole"}) + void aFailingSource_failsWithSourceReadFailed(String how) { + IOException disk = new IOException("disk"); + InputStream failing = + new InputStream() { + @Override + public int read() throws IOException { + throw disk; + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + throw disk; + } + }; + FilesExtUploadData data = FilesExtUploadData.fromStream(failing); + + SourceReadFailed e = + assertThrows( + SourceReadFailed.class, + () -> { + if (how.equals("read")) { + data.nextPart(4); + } else { + readToEnd(data.whole()); + } + }); + assertSame(disk, e.getCause()); + } + + static List aStreamFailingPartway() { + return Arrays.asList( + Arguments.of("failing on its first read, reading a part", 0, "part", true), + Arguments.of("failing after 3 bytes, reading a part", 3, "part", false), + Arguments.of("failing after 3 bytes, reading ahead", 3, "ahead", false)); + } + + @ParameterizedTest(name = "{0}") + @MethodSource + void aStreamFailingPartway( + String name, int bytesBeforeFailure, String how, boolean canSendAgain) { + FilesExtUploadData data = + FilesExtUploadData.fromStream(failingAfter(bytesBeforeFailure, new IOException("disk"))); + + assertThrows( + SourceReadFailed.class, + () -> { + if (how.equals("part")) { + data.nextPart(CONTENT.length); + } else { + data.readAhead(CONTENT.length); + } + }); + assertEquals(canSendAgain, data.canSendAgain()); + } + + /** A stream that returns {@code n} bytes of CONTENT, one read each, then throws {@code e}. */ + private static InputStream failingAfter(int n, IOException e) { + return new InputStream() { + private int served; + + @Override + public int read() throws IOException { + if (served >= n) { + throw e; + } + return CONTENT[served++] & 0xff; + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + if (served >= n) { + throw e; + } + b[off] = CONTENT[served++]; + return 1; + } + }; + } + + @ParameterizedTest + @ValueSource(strings = {"file", "channel"}) + void readWhileInterrupted_leavesTheChannelOpenAndKeepsTheInterrupt(String source) + throws IOException { + FilesExtUploadData data = data(source, CONTENT); + Thread.currentThread().interrupt(); + try { + // An interrupted FileChannel read would close the channel for good. + assertArrayEquals(Arrays.copyOf(CONTENT, 4), data.nextPart(4).data); + assertArrayEquals(CONTENT, readToEnd(data.whole())); + assertTrue(Thread.currentThread().isInterrupted()); + } finally { + Thread.interrupted(); + } + assertArrayEquals(Arrays.copyOfRange(CONTENT, 4, 8), data.nextPart(4).data); + } + + @Test + void theCallersChannelClosedByAnInterrupt_failsWithSourceReadFailedAndKeepsTheInterrupt() + throws IOException { + SeekableByteChannel interrupted = new InterruptedChannel(channel(CONTENT)); + FilesExtUploadData data = FilesExtUploadData.fromChannel(interrupted); + try { + SourceReadFailed e = assertThrows(SourceReadFailed.class, () -> data.nextPart(4)); + + assertTrue(e.getCause() instanceof ClosedByInterruptException); + assertTrue(Thread.currentThread().isInterrupted()); + } finally { + Thread.interrupted(); + } + } + + @Test + void aChannelReadingNothing_failsWithSourceReadFailedInsteadOfSpinning() throws IOException { + FilesExtUploadData data = + FilesExtUploadData.fromChannel(new NonBlockingChannel(channel(CONTENT))); + + SourceReadFailed e = assertThrows(SourceReadFailed.class, () -> data.nextPart(4)); + + assertTrue(e.getCause().getMessage().contains("non-blocking"), e.getCause().getMessage()); + } + + @Test + void closingWhole_leavesTheUsersStreamOpen() throws IOException { + ClosingStream stream = new ClosingStream(new ByteArrayInputStream(CONTENT)); + FilesExtUploadData data = FilesExtUploadData.fromStream(stream); + + data.whole().close(); + + assertFalse(stream.closed); + } + + @ParameterizedTest + @ValueSource(strings = {"one-pass", "short-reads"}) + void whole_ofAStreamNotReadAheadInFull_cannotBeSentAgainOnceReturned(String source) + throws IOException { + FilesExtUploadData data = data(source, CONTENT); + + data.whole(); + + // Before the body is read: a retry must not resend it. + assertFalse(data.canSendAgain()); + } + + @Test + void aStreamFailingOnReadAhead_failsWithSourceReadFailed() { + FilesExtUploadData data = FilesExtUploadData.fromStream(new FailingStream()); + + assertThrows(SourceReadFailed.class, () -> data.readAhead(4)); + } + + @Test + void aOnePassStreamOver2GiB_isReadToTheEndAfterCommit() throws IOException { + long size = 3L * 1024 * 1024 * 1024 + 5; + FilesExtUploadData data = FilesExtUploadData.fromStream(new Zeros(size)); + int partSize = 64 * 1024 * 1024; + data.nextPart(partSize); + data.dropReplayBuffer(); + + long total = partSize; + int parts = 1; + for (Part p = data.nextPart(partSize); p != null; p = data.nextPart(partSize)) { + total += p.data.length; + parts = p.number; + } + + assertEquals(size, total); + assertEquals(Long.valueOf(size), data.sizeOrNull()); + assertEquals(49, parts); + assertEquals(0, data.keptBytes()); + } + + @Test + void aMissingFile_failsWithSourceReadFailedOnRead() throws IOException { + Path path = Files.write(tempDir.resolve("gone"), CONTENT); + FilesExtUploadData data = FilesExtUploadData.fromFile(path); + Files.delete(path); + + assertThrows(SourceReadFailed.class, () -> data.nextPart(4)); + } + + private FilesExtUploadData data(String source, byte[] content) throws IOException { + FilesExtUploadData data; + switch (source) { + case "file": + data = FilesExtUploadData.fromFile(Files.write(tempDir.resolve("source"), content)); + break; + case "channel": + data = FilesExtUploadData.fromChannel(channel(content)); + break; + case "one-pass": + data = FilesExtUploadData.fromStream(new ByteArrayInputStream(content)); + break; + case "short-reads": + data = FilesExtUploadData.fromStream(new ShortReads(content, 3)); + break; + default: + throw new AssertionError(source); + } + opened.add(data); + return data; + } + + private SeekableByteChannel channel(byte[] content) throws IOException { + Path path = Files.write(Files.createTempFile(tempDir, "channel", ".bin"), content); + FileChannel channel = FileChannel.open(path, StandardOpenOption.READ); + opened.add(channel); + return channel; + } + + private static boolean rewindable(String source) { + return source.equals("file") || source.equals("channel"); + } + + private static List allParts(FilesExtUploadData data, int size) throws IOException { + List parts = new ArrayList<>(); + for (Part p = data.nextPart(size); p != null; p = data.nextPart(size)) { + parts.add(p); + } + return parts; + } + + /** Asserts the parts' numbers and that part i holds CONTENT[bounds[i], bounds[i + 1]). */ + private static void assertParts(List parts, int[] numbers, int... bounds) { + assertEquals(numbers.length, parts.size()); + for (int i = 0; i < numbers.length; i++) { + assertEquals(numbers[i], parts.get(i).number); + assertArrayEquals(Arrays.copyOfRange(CONTENT, bounds[i], bounds[i + 1]), parts.get(i).data); + } + } + + private static byte[] join(List parts) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (Part p : parts) { + out.write(p.data, 0, p.data.length); + } + return out.toByteArray(); + } + + /** As an HTTP client sends a body: reads until the end, a few bytes at a time. */ + private static byte[] readToEnd(InputStream in) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] chunk = new byte[4]; + for (int n = in.read(chunk); n >= 0; n = in.read(chunk)) { + out.write(chunk, 0, n); + } + return out.toByteArray(); + } + + /** A pipe-like stream that returns fewer bytes than asked for before it ends. */ + private static final class ShortReads extends FilterInputStream { + private final int most; + + ShortReads(byte[] content, int most) { + super(new ByteArrayInputStream(content)); + this.most = most; + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + return super.read(b, off, Math.min(len, most)); + } + } + + /** A stream that fails every read. */ + private static final class FailingStream extends InputStream { + @Override + public int read() throws IOException { + throw new IOException("disk"); + } + } + + /** A one-pass stream of {@code size} zero bytes, generated as read. */ + private static final class Zeros extends InputStream { + private long left; + + Zeros(long size) { + left = size; + } + + @Override + public int read() { + return left-- > 0 ? 0 : -1; + } + + @Override + public int read(byte[] b, int off, int len) { + if (left <= 0) { + return -1; + } + int n = (int) Math.min(len, left); + Arrays.fill(b, off, off + n, (byte) 0); + left -= n; + return n; + } + } + + /** A channel whose reads fail as an interrupted FileChannel read does: closed by it. */ + private static final class InterruptedChannel extends ReadOverride { + InterruptedChannel(SeekableByteChannel delegate) { + super(delegate); + } + + @Override + public int read(ByteBuffer dst) throws IOException { + Thread.currentThread().interrupt(); + throw new ClosedByInterruptException(); + } + } + + /** A channel that reads nothing, as a non-blocking channel with no bytes ready does. */ + private static final class NonBlockingChannel extends ReadOverride { + NonBlockingChannel(SeekableByteChannel delegate) { + super(delegate); + } + + @Override + public int read(ByteBuffer dst) { + return 0; + } + } + + /** A channel over another, whose subclass decides what a read does. */ + private abstract static class ReadOverride implements SeekableByteChannel { + private final SeekableByteChannel delegate; + + ReadOverride(SeekableByteChannel delegate) { + this.delegate = delegate; + } + + @Override + public int write(ByteBuffer src) { + throw new UnsupportedOperationException(); + } + + @Override + public long position() throws IOException { + return delegate.position(); + } + + @Override + public SeekableByteChannel position(long newPosition) throws IOException { + delegate.position(newPosition); + return this; + } + + @Override + public long size() throws IOException { + return delegate.size(); + } + + @Override + public SeekableByteChannel truncate(long size) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean isOpen() { + return delegate.isOpen(); + } + + @Override + public void close() throws IOException { + delegate.close(); + } + } + + private static final class ClosingStream extends FilterInputStream { + boolean closed; + + ClosingStream(InputStream in) { + super(in); + } + + @Override + public void close() throws IOException { + closed = true; + super.close(); + } + } +} diff --git a/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtUploadPlanTest.java b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtUploadPlanTest.java new file mode 100644 index 000000000..958907a4a --- /dev/null +++ b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtUploadPlanTest.java @@ -0,0 +1,178 @@ +package com.databricks.sdk.mixin; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.databricks.sdk.mixin.FilesExtUploadPlan.PartSizing; +import com.databricks.sdk.mixin.FilesExtUploadPlan.UploadCapabilities; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +/** The upload planning and part-size policy. */ +public class FilesExtUploadPlanTest { + private static final long MIB = 1024 * 1024; + private static final long GIB = 1024 * MIB; + + @ParameterizedTest(name = "{0}") + @CsvSource({ + // name, size, min multipart size, single shot, multipart, max part, max single shot, + // parallel, then the plan (multipart, part size, parallelism) or "none" + "small, 5, 10, true, true, , , false, false/4/1", + "small without single shot, 5, 10, false, true, , , false, none", + "at the threshold, 10, 10, true, true, , , false, true/4/1", + "empty, 0, 0, true, true, , , true, false/4/1", + "no multipart, 100, 10, true, false, , , true, false/4/1", + "sequential, 100, 10, true, true, , , false, true/4/1", + "parallel, 100, 10, true, true, , , true, true/4/3", + "capped part size, 100, 10, true, true, 2, , true, true/2/3", + "single shot at limit, 100, 10, true, false, , 100, false, false/4/1", + "single shot over limit, 100, 10, true, false, , 99, false, none" + }) + void plan( + String name, + long size, + int minMultipartSize, + boolean singleShot, + boolean multipart, + Long maxPartSize, + Long maxSingleShotSize, + boolean parallel, + String expected) { + FilesExtUploadPlan plan = + FilesExtUploadPlan.plan( + size, + client(singleShot, multipart, maxPartSize, maxSingleShotSize), + parallel, + 3, + 4, + 1, + minMultipartSize); + + assertEquals( + expected, + plan == null ? "none" : plan.multipart + "/" + plan.partSize + "/" + plan.parallelism); + } + + @Test + void plan_sendsAOnePassStreamOfUnknownSizeMultipart() throws IOException { + FilesExtUploadData data = FilesExtUploadData.fromStream(new ByteArrayInputStream(new byte[5])); + UploadCapabilities client = client(true, true, null, null); + + assertTrue(FilesExtUploadPlan.plan(data.sizeOrNull(), client, false, 3, 4, 1, 10).multipart); + data.readAhead(10); + assertFalse(FilesExtUploadPlan.plan(data.sizeOrNull(), client, false, 3, 4, 1, 10).multipart); + } + + @Test + void plan_unknownSizeWithASingleShotLimit_staysMultipart() { + UploadCapabilities client = client(true, true, null, 100L); + + assertTrue(FilesExtUploadPlan.plan(null, client, false, 3, 4, 1, 10).multipart); + } + + @Test + void plan_sequentialUsesTheBatchSize_parallelAsksForOneUrlAtATime() { + UploadCapabilities client = client(true, true, null, null); + + assertEquals(5, FilesExtUploadPlan.plan(100L, client, false, 3, 4, 5, 10).batchSize); + assertEquals(1, FilesExtUploadPlan.plan(100L, client, true, 3, 4, 5, 10).batchSize); + } + + @Test + void plan_parallelismZeroOrUnset_isOne() { + UploadCapabilities client = client(true, true, null, null); + + assertEquals(1, FilesExtUploadPlan.plan(100L, client, true, 0, 4, 1, 10).parallelism); + assertEquals(1, FilesExtUploadPlan.plan(100L, client, true, null, 4, 1, 10).parallelism); + } + + @ParameterizedTest(name = "{0} bytes -> {1} byte parts, batch {2}") + @CsvSource({ + // At most 100 parts with the smallest option; the batch is ceil(sqrt(parts)). + "1, 10485760, 1", + "1048576000, 10485760, 10", + "1048576001, 20971520, 8", + "107374182400, 1073741824, 10", + // Over 100 GiB, Java stays at its 1 GiB maximum: a 1 TiB file is 1,024 parts. + "1099511627776, 1073741824, 32", + "0, 10485760, 0" + }) + void partSizing_picksTheSmallestOptionWithAtMost100Parts(long size, int partSize, int batch) { + PartSizing sizing = FilesExtUploadPlan.partSizing(size, null); + + assertEquals(partSize, sizing.partSize); + assertEquals(batch, sizing.batchSize); + } + + @Test + void partSizing_aTebibyte_plans1024PartsOf1GiB() { + PartSizing sizing = FilesExtUploadPlan.partSizing(1024 * GIB, null); + + assertEquals(GIB, sizing.partSize); + assertEquals(1024, FilesExtUploadPlan.partCount(1024 * GIB, sizing.partSize)); + } + + @Test + void partSizing_unknownSize_usesTheDefaults() { + PartSizing sizing = FilesExtUploadPlan.partSizing(null, null); + + assertEquals(10 * MIB, sizing.partSize); + assertEquals(1, sizing.batchSize); + } + + @Test + void partSizing_aGivenPartSize_isUsedAsIs() { + PartSizing sizing = FilesExtUploadPlan.partSizing(1000L, 7); + + assertEquals(7, sizing.partSize); + assertEquals(12, sizing.batchSize); + assertEquals(GIB, FilesExtUploadPlan.partSizing(null, (int) GIB).partSize); + } + + @ParameterizedTest + @ValueSource(ints = {1073741825, Integer.MAX_VALUE, 0, -1}) + void partSizing_rejectsAPartSizeOver1GiBOrNotPositive(int partSize) { + assertThrows( + IllegalArgumentException.class, () -> FilesExtUploadPlan.partSizing(100L, partSize)); + } + + @Test + void partSizeOptions_endAtTheMaximum() { + assertEquals( + FilesExtUploadPlan.MAX_PART_SIZE, + (int) + FilesExtUploadPlan.PART_SIZE_OPTIONS.get( + FilesExtUploadPlan.PART_SIZE_OPTIONS.size() - 1)); + } + + private static UploadCapabilities client( + boolean singleShot, boolean multipart, Long maxPartSize, Long maxSingleShotSize) { + return new UploadCapabilities() { + @Override + public boolean supportsMultipart() { + return multipart; + } + + @Override + public boolean supportsSingleShot() { + return singleShot; + } + + @Override + public Long maxSingleShotSizeOrNull() { + return maxSingleShotSize; + } + + @Override + public Long maxPartSizeOrNull() { + return maxPartSize; + } + }; + } +} diff --git a/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtUploadWalkTest.java b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtUploadWalkTest.java new file mode 100644 index 000000000..8021459b6 --- /dev/null +++ b/databricks-sdk-java/src/test/java/com/databricks/sdk/mixin/FilesExtUploadWalkTest.java @@ -0,0 +1,794 @@ +package com.databricks.sdk.mixin; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.databricks.sdk.core.DatabricksError; +import com.databricks.sdk.core.DatabricksException; +import com.databricks.sdk.core.utils.SystemTimer; +import com.databricks.sdk.mixin.FilesExtRetry.Budget; +import com.databricks.sdk.mixin.FilesExtRetry.Decision; +import com.databricks.sdk.mixin.FilesExtRetry.Failure; +import com.databricks.sdk.mixin.FilesExtRetry.RequestFailed; +import com.databricks.sdk.mixin.FilesExtRetry.Result; +import com.databricks.sdk.mixin.FilesExtRetry.TransferStatus; +import com.databricks.sdk.mixin.FilesExtUploadWalk.MultipartSession; +import com.databricks.sdk.mixin.FilesExtUploadWalk.UploadClient; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** The upload walk, and its threads: bounded, gone on return, never interrupted. */ +public class FilesExtUploadWalkTest { + private static final byte[] TEN = "0123456789".getBytes(UTF_8); + + @TempDir Path tempDir; + + // --- runInParallel --- + + @Test + void runInParallel_cancelsTheOtherThreadsOnTheFirstFailure() { + Failure failure = walk("first"); + TransferStatus status = new TransferStatus(true, 0); + Set started = ConcurrentHashMap.newKeySet(); + Iterator items = IntStream.range(0, 100).boxed().iterator(); + + Failure result = + FilesExtUploadWalk.runInParallel( + 4, + () -> items.hasNext() ? items.next() : null, + (item, s) -> { + started.add(item); + if (item == 0) { + return failure; + } + // The other items run until the failure cancels them. + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (!s.cancelled() && System.nanoTime() < deadline) { + Thread.yield(); + } + return walk("cancelled " + item); + }, + status); + + assertSame(failure, result); + assertTrue(status.cancelled()); + assertTrue(started.size() <= 4, started.toString()); + } + + @ParameterizedTest + @ValueSource(strings = {"next", "work"}) + void runInParallel_turnsAnExceptionIntoAWalkFailure(String raisesIn) { + IllegalStateException error = new IllegalStateException("unexpected"); + + Failure failure = + FilesExtUploadWalk.runInParallel( + 2, + () -> { + if (raisesIn.equals("next")) { + throw error; + } + return 1; + }, + (item, s) -> { + throw error; + }, + new TransferStatus(true, 0)); + + assertSame(error, failure.error); + assertEquals(Decision.WALK, failure.decision); + } + + @ParameterizedTest + @ValueSource(strings = {"next", "work"}) + void runInParallel_onTheCallingThread_letsAnInterruptThrough(String raisesIn) { + DatabricksException interrupt = + new DatabricksException("Current thread was interrupted", new InterruptedException()); + try { + DatabricksException e = + assertThrows( + DatabricksException.class, + () -> + FilesExtUploadWalk.runInParallel( + 1, + () -> { + if (raisesIn.equals("next")) { + Thread.currentThread().interrupt(); + throw interrupt; + } + return 1; + }, + (item, s) -> { + Thread.currentThread().interrupt(); + throw interrupt; + }, + new TransferStatus(true, 0))); + + assertSame(interrupt, e); + } finally { + Thread.interrupted(); + } + } + + @Test + void runInParallel_stopsAtTheFirstFailure() { + Failure failure = walk("third"); + TransferStatus status = new TransferStatus(true, 0); + List done = new ArrayList<>(); + Iterator items = IntStream.range(0, 100).boxed().iterator(); + + Failure result = + FilesExtUploadWalk.runInParallel( + 1, + () -> items.hasNext() ? items.next() : null, + (item, s) -> { + if (item == 3) { + return failure; + } + done.add(item); + return null; + }, + status); + + assertSame(failure, result); + assertTrue(status.cancelled()); + assertEquals(Arrays.asList(0, 1, 2), done); + } + + @Test + void runInParallel_runsEveryItem_andLeavesNoThreads() throws InterruptedException { + Set done = ConcurrentHashMap.newKeySet(); + Iterator items = IntStream.range(0, 50).boxed().iterator(); + + Failure result = + FilesExtUploadWalk.runInParallel( + 4, + () -> items.hasNext() ? items.next() : null, + (item, s) -> { + done.add(item); + return null; + }, + new TransferStatus(true, 0)); + + assertNull(result); + assertEquals(IntStream.range(0, 50).boxed().collect(Collectors.toSet()), done); + assertEquals(Collections.emptyList(), transferThreads()); + } + + // --- uploadTo --- + + @ParameterizedTest + @ValueSource(ints = {1, 3}) + void uploadTo_commitsOnTheFirstPartAndCompletes(int parallelism) throws Exception { + Session session = new Session(); + Client client = new Client(session); + TransferStatus status = new TransferStatus(true, 0); + FilesExtUploadData data = FilesExtUploadData.fromStream(new ByteArrayInputStream(TEN)); + FilesExtUploadPlan plan = + FilesExtUploadPlan.plan(data.sizeOrNull(), client, parallelism > 1, parallelism, 4, 1, 0); + + assertNull(FilesExtUploadWalk.uploadTo(client, status, plan, "/f", null, data)); + + assertTrue(status.committed()); + assertEquals("0123|4567|89", session.partsJoined()); + assertEquals("{1=etag-1, 2=etag-2, 3=etag-3}", String.valueOf(session.completed)); + assertEquals(0, session.aborts.get()); + assertEquals(Collections.emptyList(), transferThreads()); + } + + @ParameterizedTest + @ValueSource(ints = {1, 2}) + void uploadTo_abortsOnceOnFailure(int failOn) throws IOException { + Session session = new Session(failOn); + Client client = new Client(session); + TransferStatus status = new TransferStatus(true, 0); + FilesExtUploadData data = FilesExtUploadData.fromStream(new ByteArrayInputStream(TEN)); + + Failure failure = + FilesExtUploadWalk.uploadTo( + client, status, new FilesExtUploadPlan(true, 4, 1, 1), "/f", null, data); + + assertEquals(Decision.WALK, failure.decision); + assertEquals(failOn == 2, status.committed()); + assertEquals(1, session.aborts.get()); + assertNull(session.completed); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void uploadTo_singleShotCommitsOnlyOnSuccess(boolean fails) throws IOException { + Failure failure = walk("put"); + List puts = new ArrayList<>(); + Client client = + new Client(null) { + @Override + public Failure putFile( + String path, Boolean overwrite, FilesExtUploadData data, TransferStatus status) { + puts.add(readAll(data)); + return fails ? failure : null; + } + }; + TransferStatus status = new TransferStatus(true, 0); + FilesExtUploadData data = FilesExtUploadData.fromStream(new ByteArrayInputStream(TEN)); + + Failure result = + FilesExtUploadWalk.uploadTo( + client, status, new FilesExtUploadPlan(false, 4, 1, 1), "/f", null, data); + + assertSame(fails ? failure : null, result); + assertEquals(!fails, status.committed()); + assertEquals(Collections.singletonList("0123456789"), puts); + } + + @Test + void uploadTo_returnsAnInitiateFailureWithoutSendingParts() { + Failure failure = walk("initiate"); + Client client = + new Client(null) { + @Override + public Result initiateUpload( + String path, Boolean overwrite, TransferStatus status, int batchSize) { + return Result.failed(failure); + } + }; + TransferStatus status = new TransferStatus(true, 0); + FilesExtUploadData data = FilesExtUploadData.fromStream(new ByteArrayInputStream(TEN)); + + Failure result = + FilesExtUploadWalk.uploadTo( + client, status, new FilesExtUploadPlan(true, 4, 1, 1), "/f", null, data); + + assertSame(failure, result); + assertFalse(status.committed()); + assertTrue(data.canSendAgain()); + } + + @Test + void uploadTo_abortsWhenCompleteFails() { + Failure failure = walk("complete"); + Session session = new Session(); + session.completeFailure = failure; + Client client = new Client(session); + TransferStatus status = new TransferStatus(true, 0); + FilesExtUploadData data = FilesExtUploadData.fromStream(new ByteArrayInputStream(TEN)); + + Failure result = + FilesExtUploadWalk.uploadTo( + client, status, new FilesExtUploadPlan(true, 4, 1, 7), "/f", null, data); + + assertSame(failure, result); + assertTrue(status.committed()); + assertEquals(1, session.aborts.get()); + assertEquals(Collections.singletonList(7), client.batchSizes); + } + + @Test + void uploadTo_throwsForAMultipartUploadOfEmptyData() { + Session session = new Session(); + Client client = new Client(session); + FilesExtUploadData data = FilesExtUploadData.fromStream(new ByteArrayInputStream(new byte[0])); + + IllegalStateException e = + assertThrows( + IllegalStateException.class, + () -> + FilesExtUploadWalk.uploadTo( + client, + new TransferStatus(true, 0), + new FilesExtUploadPlan(true, 4, 1, 1), + "/f", + null, + data)); + + assertTrue(e.getMessage().contains("empty data"), e.getMessage()); + assertEquals(1, session.aborts.get()); + } + + // --- upload --- + + @Test + void upload_walksToTheNextEndpointBeforeCommitFromTheStart() throws IOException { + Session failing = new Session(1); + Session working = new Session(); + Client first = new Client(failing, "first"); + Client second = new Client(working, "second"); + ClosingStream stream = new ClosingStream(TEN); + + FilesExtUploadWalk.upload( + Arrays.asList(first, second), + FilesExtUploadData.fromStream(stream), + "/f", + null, + 4, + 1, + false, + null, + 0); + + assertEquals(1, failing.aborts.get()); + assertEquals("0123|4567|89", working.partsJoined()); + assertFalse(stream.closed); + } + + @ParameterizedTest + @ValueSource(ints = {0, 3}) + void upload_readsAShortStreamOfUnknownSizeAheadAndSendsItInOneShot(int length) + throws IOException { + List puts = new ArrayList<>(); + Client client = + new Client(new Session()) { + @Override + public Failure putFile( + String path, Boolean overwrite, FilesExtUploadData data, TransferStatus status) { + puts.add(readAll(data)); + return null; + } + }; + + FilesExtUploadWalk.upload( + Collections.singletonList(client), + FilesExtUploadData.fromStream(new ByteArrayInputStream(Arrays.copyOf(TEN, length))), + "/f", + null, + 4, + 1, + false, + null, + 10); + + assertEquals(Collections.singletonList(new String(Arrays.copyOf(TEN, length), UTF_8)), puts); + assertEquals(Collections.emptyList(), client.batchSizes); + } + + @Test + void upload_withOnlySingleShotClientsUnderTheSize_throws() throws IOException { + Client small = + new Client(null, "workspace") { + @Override + public boolean supportsMultipart() { + return false; + } + + @Override + public Long maxSingleShotSizeOrNull() { + return 5L; + } + }; + Path file = Files.write(tempDir.resolve("big"), TEN); + + IllegalArgumentException e = + assertThrows( + IllegalArgumentException.class, + () -> + FilesExtUploadWalk.upload( + Collections.singletonList(small), + FilesExtUploadData.fromFile(file), + "/f", + null, + 4, + 1, + false, + null, + 0)); + + assertTrue( + e.getMessage().startsWith("No endpoint can take this upload of 10 bytes: workspace")); + } + + // --- interrupts --- + + @Test + void interruptedParallelUpload_returnsOnlyOnceTheInFlightPartsFinish() throws Exception { + Path file = Files.write(tempDir.resolve("source"), new byte[40]); + FileChannel channel = FileChannel.open(file, StandardOpenOption.READ); + CountDownLatch release = new CountDownLatch(1); + CountDownLatch inFlight = new CountDownLatch(2); + AtomicInteger afterInterrupt = new AtomicInteger(); + AtomicBoolean interruptSent = new AtomicBoolean(); + AtomicBoolean workerInterrupted = new AtomicBoolean(); + AtomicReference transfer = new AtomicReference<>(); + AtomicBoolean workersAreDaemons = new AtomicBoolean(true); + Session session = + new Session() { + @Override + public Result putPart(int number, byte[] data, TransferStatus status) { + if (number == 1) { + return super.putPart(number, data, status); + } + if (interruptSent.get()) { + afterInterrupt.incrementAndGet(); + } + transfer.set(status); + inFlight.countDown(); + if (!Thread.currentThread().isDaemon()) { + workersAreDaemons.set(false); + } + // A request that only the server can end: not interruptible. + if (awaitUninterruptibly(release)) { + workerInterrupted.set(true); + } + return super.putPart(number, data, status); + } + }; + Client client = new Client(session); + AtomicReference thrown = new AtomicReference<>(); + AtomicBoolean interruptedOnReturn = new AtomicBoolean(); + Thread caller = + new Thread( + () -> { + try { + FilesExtUploadWalk.upload( + Collections.singletonList(client), + FilesExtUploadData.fromChannel(channel), + "/f", + null, + 4, + 1, + true, + 2, + 0); + } catch (Throwable t) { + thrown.set(t); + } + interruptedOnReturn.set(Thread.currentThread().isInterrupted()); + }); + caller.start(); + assertTrue(inFlight.await(10, TimeUnit.SECONDS)); + + interruptSent.set(true); + caller.interrupt(); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (!transfer.get().cancelled() && System.nanoTime() < deadline) { + Thread.sleep(10); + } + assertTrue(transfer.get().cancelled()); + caller.join(200); + // Still waiting for the requests in flight. + assertTrue(caller.isAlive()); + release.countDown(); + caller.join(10_000); + + assertFalse(caller.isAlive()); + assertTrue(thrown.get() instanceof DatabricksException, String.valueOf(thrown.get())); + assertEquals("Current thread was interrupted", thrown.get().getMessage()); + assertTrue(interruptedOnReturn.get()); + assertEquals(0, afterInterrupt.get()); + // The workers are never interrupted: that could close the caller's channel mid-read. + assertFalse(workerInterrupted.get()); + assertTrue(workersAreDaemons.get()); + assertEquals(1, session.aborts.get()); + assertNull(session.completed); + assertTrue(channel.isOpen()); + assertEquals(Collections.emptyList(), transferThreads()); + channel.close(); + } + + @Test + void interruptedParallelUpload_wakesARetryBackoffWithinASecond() throws Exception { + CountDownLatch backingOff = new CountDownLatch(1); + Session session = + new Session() { + @Override + public Result putPart(int number, byte[] data, TransferStatus status) { + if (number == 1) { + return super.putPart(number, data, status); + } + // The server asks for 60 s: the retry loop waits in steps that see cancellation. + return FilesExtRetry.retry( + () -> { + backingOff.countDown(); + throw new RequestFailed( + new DatabricksError("THROTTLED", "slow down", 429), 429, null, 60L); + }, + FilesExtRetry::commonDecision, + new Budget(null, Duration.ofMinutes(5)), + status, + new SystemTimer()); + } + }; + Client client = new Client(session); + AtomicReference thrown = new AtomicReference<>(); + Thread caller = + new Thread( + () -> { + try { + FilesExtUploadWalk.upload( + Collections.singletonList(client), + FilesExtUploadData.fromStream(new ByteArrayInputStream(TEN)), + "/f", + null, + 4, + 1, + true, + 2, + 0); + } catch (Throwable t) { + thrown.set(t); + } + }); + caller.start(); + assertTrue(backingOff.await(10, TimeUnit.SECONDS)); + Thread.sleep(100); + + long interruptedAt = System.nanoTime(); + caller.interrupt(); + caller.join(10_000); + long tookMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - interruptedAt); + + assertFalse(caller.isAlive()); + // The backoff asked for 60 s; its 1 s steps see the cancellation. + assertTrue(tookMillis < 5000, tookMillis + " ms"); + assertEquals("Current thread was interrupted", thrown.get().getMessage()); + assertEquals(1, session.aborts.get()); + assertEquals(Collections.emptyList(), transferThreads()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void interruptAfterASuccessfulPart_stopsBeforeTheNextOne(boolean parallel) throws Exception { + Session session = + new Session() { + @Override + public Result putPart(int number, byte[] data, TransferStatus status) { + Result etag = super.putPart(number, data, status); + if (number == (parallel ? 1 : 2)) { + // The caller's thread is interrupted while this part succeeds. + Thread.currentThread().interrupt(); + } + return etag; + } + }; + try { + DatabricksException e = + assertThrows( + DatabricksException.class, + () -> + FilesExtUploadWalk.upload( + Collections.singletonList(new Client(session)), + FilesExtUploadData.fromStream(new ByteArrayInputStream(TEN)), + "/f", + null, + 4, + 1, + parallel, + 2, + 0)); + + assertEquals("Current thread was interrupted", e.getMessage()); + assertTrue(Thread.currentThread().isInterrupted()); + assertEquals(parallel ? "0123" : "0123|4567", session.partsJoined()); + assertEquals(1, session.aborts.get()); + assertNull(session.completed); + } finally { + Thread.interrupted(); + } + assertEquals(Collections.emptyList(), transferThreads()); + } + + @Test + void interruptedSequentialUpload_abortsOnceAndThrowsTheInterrupt() throws IOException { + Session session = + new Session() { + @Override + public Result putPart(int number, byte[] data, TransferStatus status) { + if (number == 2) { + // As the retry loop fails when its thread is interrupted. + Thread.currentThread().interrupt(); + throw new DatabricksException( + "Current thread was interrupted", new InterruptedException()); + } + return super.putPart(number, data, status); + } + }; + Client client = new Client(session); + try { + DatabricksException e = + assertThrows( + DatabricksException.class, + () -> + FilesExtUploadWalk.upload( + Arrays.asList(client, new Client(new Session(), "next")), + FilesExtUploadData.fromStream(new ByteArrayInputStream(TEN)), + "/f", + null, + 4, + 1, + false, + null, + 0)); + + assertEquals("Current thread was interrupted", e.getMessage()); + assertTrue(Thread.currentThread().isInterrupted()); + assertEquals(1, session.aborts.get()); + } finally { + Thread.interrupted(); + } + } + + // --- helpers --- + + private static Failure walk(String message) { + return new Failure(new IllegalStateException(message), Decision.WALK); + } + + /** + * The transfer threads still alive. A pool is terminated just before its last thread exits, so + * each is given a moment to finish exiting first. + */ + private static List transferThreads() throws InterruptedException { + List names = new ArrayList<>(); + for (Thread t : Thread.getAllStackTraces().keySet()) { + if (t.getName().startsWith(FilesExtUploadWalk.TRANSFER_THREAD_NAME)) { + t.join(5000); + if (t.isAlive()) { + names.add(t.getName()); + } + } + } + return names; + } + + /** Waits for the latch: whether the thread was interrupted while waiting. */ + private static boolean awaitUninterruptibly(CountDownLatch latch) { + boolean interrupted = false; + while (true) { + try { + latch.await(); + break; + } catch (InterruptedException e) { + interrupted = true; + } + } + return interrupted; + } + + private static String readAll(FilesExtUploadData data) { + try (InputStream in = data.whole()) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] chunk = new byte[4]; + for (int n = in.read(chunk); n >= 0; n = in.read(chunk)) { + out.write(chunk, 0, n); + } + return new String(out.toByteArray(), UTF_8); + } catch (IOException e) { + throw new AssertionError(e); + } + } + + /** A multipart session recording parts, failing the part numbers given. */ + private static class Session implements MultipartSession { + final Map parts = new ConcurrentHashMap<>(); + final AtomicInteger aborts = new AtomicInteger(); + final List failOn; + volatile Map completed; + Failure completeFailure; + + Session(Integer... failOn) { + this.failOn = Arrays.asList(failOn); + } + + @Override + public Result putPart(int number, byte[] data, TransferStatus status) { + if (failOn.contains(number)) { + return Result.failed(walk("part " + number)); + } + parts.put(number, data); + return Result.of("etag-" + number); + } + + @Override + public Failure complete(Map etags, TransferStatus status) { + completed = new TreeMap<>(etags); + return completeFailure; + } + + @Override + public void abort() { + aborts.incrementAndGet(); + } + + String partsJoined() { + return new TreeMap<>(parts) + .values().stream().map(b -> new String(b, UTF_8)).collect(Collectors.joining("|")); + } + } + + /** An endpoint client with single shot and multipart, opening the given session. */ + private static class Client implements UploadClient { + private final Session session; + private final String name; + final List batchSizes = new ArrayList<>(); + + Client(Session session) { + this(session, "a"); + } + + Client(Session session, String name) { + this.session = session; + this.name = name; + } + + @Override + public String name() { + return name; + } + + @Override + public boolean supportsMultipart() { + return true; + } + + @Override + public boolean supportsSingleShot() { + return true; + } + + @Override + public Long maxSingleShotSizeOrNull() { + return null; + } + + @Override + public Long maxPartSizeOrNull() { + return null; + } + + @Override + public Failure putFile( + String path, Boolean overwrite, FilesExtUploadData data, TransferStatus status) { + throw new AssertionError("no single shot expected"); + } + + @Override + public Result initiateUpload( + String path, Boolean overwrite, TransferStatus status, int batchSize) { + batchSizes.add(batchSize); + return Result.of(session); + } + } + + private static final class ClosingStream extends ByteArrayInputStream { + boolean closed; + + ClosingStream(byte[] content) { + super(content); + } + + @Override + public void close() throws IOException { + closed = true; + super.close(); + } + } +} diff --git a/examples/docs/pom.xml b/examples/docs/pom.xml index b103aace4..5d7227718 100644 --- a/examples/docs/pom.xml +++ b/examples/docs/pom.xml @@ -24,7 +24,7 @@ com.databricks databricks-sdk-java - 0.186.0 + 0.187.0 diff --git a/examples/spring-boot-oauth-u2m-demo/pom.xml b/examples/spring-boot-oauth-u2m-demo/pom.xml index 01951d3a4..b22279db7 100644 --- a/examples/spring-boot-oauth-u2m-demo/pom.xml +++ b/examples/spring-boot-oauth-u2m-demo/pom.xml @@ -40,7 +40,7 @@ com.databricks databricks-sdk-java - 0.186.0 + 0.187.0 diff --git a/lockfile.json b/lockfile.json index 77f1390ec..54f530d92 100644 --- a/lockfile.json +++ b/lockfile.json @@ -1,7 +1,7 @@ { "artifactId": "databricks-sdk-parent", "groupId": "com.databricks", - "version": "0.186.0", + "version": "0.187.0", "lockFileVersion": 1, "dependencies": [], "mavenPlugins": [], diff --git a/pom.xml b/pom.xml index c89417304..a349024db 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ 4.0.0 com.databricks databricks-sdk-parent - 0.186.0 + 0.187.0 pom Databricks SDK for Java The Databricks SDK for Java includes functionality to accelerate development with Java for diff --git a/shaded/pom.xml b/shaded/pom.xml index 3b51377fa..ce316ad1e 100644 --- a/shaded/pom.xml +++ b/shaded/pom.xml @@ -4,7 +4,7 @@ 4.0.0 - 0.186.0 + 0.187.0 com.databricks