comment stringlengths 1 45k | method_body stringlengths 23 281k | target_code stringlengths 0 5.16k | method_body_after stringlengths 12 281k | context_before stringlengths 8 543k | context_after stringlengths 8 543k |
|---|---|---|---|---|---|
why changing this | void configurationPropertiesShouldBind() {
String accountName = "test-account-name";
String connectionString = String.format(STORAGE_CONNECTION_STRING_PATTERN, accountName, "test-key");
String endpoint = String.format("https:
String customerProvidedKey = "fakekey";
this.contextRunner
.withPropertyValues(
"spring.cloud.azure.storage.blob.endpoint=" + endpoint,
"spring.cloud.azure.storage.blob.account-key=test-key",
"spring.cloud.azure.storage.blob.sas-token=test-sas-token",
"spring.cloud.azure.storage.blob.connection-string=" + connectionString,
"spring.cloud.azure.storage.blob.account-name=test-account-name",
"spring.cloud.azure.storage.blob.customer-provided-key=" + customerProvidedKey,
"spring.cloud.azure.storage.blob.encryption-scope=test-scope",
"spring.cloud.azure.storage.blob.service-version=V2020_08_04",
"spring.cloud.azure.storage.blob.container-name=test-container",
"spring.cloud.azure.storage.blob.blob-name=test-blob"
)
.withBean(AzureGlobalProperties.class, AzureGlobalProperties::new)
.run(context -> {
assertThat(context).hasSingleBean(AzureStorageBlobProperties.class);
AzureStorageBlobProperties properties = context.getBean(AzureStorageBlobProperties.class);
assertEquals(endpoint, properties.getEndpoint());
assertEquals("test-key", properties.getAccountKey());
assertEquals("test-sas-token", properties.getSasToken());
assertEquals(connectionString, properties.getConnectionString());
assertEquals(accountName, properties.getAccountName());
assertEquals(customerProvidedKey, properties.getCustomerProvidedKey());
assertEquals("test-scope", properties.getEncryptionScope());
assertEquals(BlobServiceVersion.V2020_08_04, properties.getServiceVersion());
assertEquals("test-container", properties.getContainerName());
assertEquals("test-blob", properties.getBlobName());
});
} | String customerProvidedKey = "fakekey"; | void configurationPropertiesShouldBind() {
String accountName = "test-account-name";
String connectionString = String.format(STORAGE_CONNECTION_STRING_PATTERN, accountName, "test-key");
String endpoint = String.format("https:
String customerProvidedKey = "fakekey";
this.contextRunner
.withPropertyValues(
"spring.cloud.azure.storage.blob.endpoint=" + endpoint,
"spring.cloud.azure.storage.blob.account-key=test-key",
"spring.cloud.azure.storage.blob.sas-token=test-sas-token",
"spring.cloud.azure.storage.blob.connection-string=" + connectionString,
"spring.cloud.azure.storage.blob.account-name=test-account-name",
"spring.cloud.azure.storage.blob.customer-provided-key=" + customerProvidedKey,
"spring.cloud.azure.storage.blob.encryption-scope=test-scope",
"spring.cloud.azure.storage.blob.service-version=V2020_08_04",
"spring.cloud.azure.storage.blob.container-name=test-container",
"spring.cloud.azure.storage.blob.blob-name=test-blob"
)
.withBean(AzureGlobalProperties.class, AzureGlobalProperties::new)
.run(context -> {
assertThat(context).hasSingleBean(AzureStorageBlobProperties.class);
AzureStorageBlobProperties properties = context.getBean(AzureStorageBlobProperties.class);
assertEquals(endpoint, properties.getEndpoint());
assertEquals("test-key", properties.getAccountKey());
assertEquals("test-sas-token", properties.getSasToken());
assertEquals(connectionString, properties.getConnectionString());
assertEquals(accountName, properties.getAccountName());
assertEquals(customerProvidedKey, properties.getCustomerProvidedKey());
assertEquals("test-scope", properties.getEncryptionScope());
assertEquals(BlobServiceVersion.V2020_08_04, properties.getServiceVersion());
assertEquals("test-container", properties.getContainerName());
assertEquals("test-blob", properties.getBlobName());
});
} | class AzureStorageBlobAutoConfigurationTests {
private static final String STORAGE_CONNECTION_STRING_PATTERN = "DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;EndpointSuffix=core.windows.net";
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(AzureStorageBlobAutoConfiguration.class));
@Test
void configureWithoutBlobServiceClientBuilder() {
this.contextRunner
.withClassLoader(new FilteredClassLoader(BlobServiceClientBuilder.class))
.withPropertyValues("spring.cloud.azure.storage.blob.account-name=sa")
.run(context -> assertThat(context).doesNotHaveBean(AzureStorageBlobAutoConfiguration.class));
}
@Test
void configureWithStorageBlobDisabled() {
this.contextRunner
.withPropertyValues(
"spring.cloud.azure.storage.blob.enabled=false",
"spring.cloud.azure.storage.blob.account-name=sa"
)
.run(context -> assertThat(context).doesNotHaveBean(AzureStorageBlobAutoConfiguration.class));
}
@Test
void accountNameSetShouldConfigure() {
this.contextRunner
.withPropertyValues("spring.cloud.azure.storage.blob.account-name=sa")
.withBean(AzureGlobalProperties.class, AzureGlobalProperties::new)
.run(context -> {
assertThat(context).hasSingleBean(AzureStorageBlobAutoConfiguration.class);
assertThat(context).hasSingleBean(AzureStorageBlobProperties.class);
assertThat(context).hasSingleBean(BlobServiceClient.class);
assertThat(context).hasSingleBean(BlobServiceAsyncClient.class);
assertThat(context).hasSingleBean(BlobServiceClientBuilder.class);
assertThat(context).hasSingleBean(BlobServiceClientBuilderFactory.class);
});
}
@Test
void containerNameSetShouldConfigureContainerClient() {
this.contextRunner
.withPropertyValues(
"spring.cloud.azure.storage.blob.account-name=sa",
"spring.cloud.azure.storage.blob.container-name=container1"
)
.withBean(AzureGlobalProperties.class, AzureGlobalProperties::new)
.run(context -> {
assertThat(context).hasSingleBean(BlobContainerClient.class);
assertThat(context).hasSingleBean(BlobContainerAsyncClient.class);
});
}
@Test
void containerNameNotSetShouldNotConfigureContainerClient() {
this.contextRunner
.withPropertyValues(
"spring.cloud.azure.storage.blob.account-name=sa"
)
.withBean(AzureGlobalProperties.class, AzureGlobalProperties::new)
.run(context -> {
assertThat(context).doesNotHaveBean(BlobContainerClient.class);
assertThat(context).doesNotHaveBean(BlobContainerAsyncClient.class);
});
}
@Test
void customizerShouldBeCalled() {
BlobServiceClientBuilderCustomizer customizer = new BlobServiceClientBuilderCustomizer();
this.contextRunner
.withPropertyValues("spring.cloud.azure.storage.blob.account-name=sa")
.withBean(AzureGlobalProperties.class, AzureGlobalProperties::new)
.withBean("customizer1", BlobServiceClientBuilderCustomizer.class, () -> customizer)
.withBean("customizer2", BlobServiceClientBuilderCustomizer.class, () -> customizer)
.run(context -> assertThat(customizer.getCustomizedTimes()).isEqualTo(2));
}
@Test
void otherCustomizerShouldNotBeCalled() {
BlobServiceClientBuilderCustomizer customizer = new BlobServiceClientBuilderCustomizer();
OtherBuilderCustomizer otherBuilderCustomizer = new OtherBuilderCustomizer();
this.contextRunner
.withPropertyValues("spring.cloud.azure.storage.blob.account-name=sa")
.withBean(AzureGlobalProperties.class, AzureGlobalProperties::new)
.withBean("customizer1", BlobServiceClientBuilderCustomizer.class, () -> customizer)
.withBean("customizer2", BlobServiceClientBuilderCustomizer.class, () -> customizer)
.withBean("customizer3", OtherBuilderCustomizer.class, () -> otherBuilderCustomizer)
.run(context -> {
assertThat(customizer.getCustomizedTimes()).isEqualTo(2);
assertThat(otherBuilderCustomizer.getCustomizedTimes()).isEqualTo(0);
});
}
@Test
private static class BlobServiceClientBuilderCustomizer extends TestBuilderCustomizer<BlobServiceClientBuilder> {
}
private static class OtherBuilderCustomizer extends TestBuilderCustomizer<ConfigurationClientBuilder> {
}
} | class AzureStorageBlobAutoConfigurationTests {
private static final String STORAGE_CONNECTION_STRING_PATTERN = "DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;EndpointSuffix=core.windows.net";
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(AzureStorageBlobAutoConfiguration.class));
@Test
void configureWithoutBlobServiceClientBuilder() {
this.contextRunner
.withClassLoader(new FilteredClassLoader(BlobServiceClientBuilder.class))
.withPropertyValues("spring.cloud.azure.storage.blob.account-name=sa")
.run(context -> assertThat(context).doesNotHaveBean(AzureStorageBlobAutoConfiguration.class));
}
@Test
void configureWithStorageBlobDisabled() {
this.contextRunner
.withPropertyValues(
"spring.cloud.azure.storage.blob.enabled=false",
"spring.cloud.azure.storage.blob.account-name=sa"
)
.run(context -> assertThat(context).doesNotHaveBean(AzureStorageBlobAutoConfiguration.class));
}
@Test
void accountNameSetShouldConfigure() {
this.contextRunner
.withPropertyValues("spring.cloud.azure.storage.blob.account-name=sa")
.withBean(AzureGlobalProperties.class, AzureGlobalProperties::new)
.run(context -> {
assertThat(context).hasSingleBean(AzureStorageBlobAutoConfiguration.class);
assertThat(context).hasSingleBean(AzureStorageBlobProperties.class);
assertThat(context).hasSingleBean(BlobServiceClient.class);
assertThat(context).hasSingleBean(BlobServiceAsyncClient.class);
assertThat(context).hasSingleBean(BlobServiceClientBuilder.class);
assertThat(context).hasSingleBean(BlobServiceClientBuilderFactory.class);
});
}
@Test
void containerNameSetShouldConfigureContainerClient() {
this.contextRunner
.withPropertyValues(
"spring.cloud.azure.storage.blob.account-name=sa",
"spring.cloud.azure.storage.blob.container-name=container1"
)
.withBean(AzureGlobalProperties.class, AzureGlobalProperties::new)
.run(context -> {
assertThat(context).hasSingleBean(BlobContainerClient.class);
assertThat(context).hasSingleBean(BlobContainerAsyncClient.class);
});
}
@Test
void containerNameNotSetShouldNotConfigureContainerClient() {
this.contextRunner
.withPropertyValues(
"spring.cloud.azure.storage.blob.account-name=sa"
)
.withBean(AzureGlobalProperties.class, AzureGlobalProperties::new)
.run(context -> {
assertThat(context).doesNotHaveBean(BlobContainerClient.class);
assertThat(context).doesNotHaveBean(BlobContainerAsyncClient.class);
});
}
@Test
void customizerShouldBeCalled() {
BlobServiceClientBuilderCustomizer customizer = new BlobServiceClientBuilderCustomizer();
this.contextRunner
.withPropertyValues("spring.cloud.azure.storage.blob.account-name=sa")
.withBean(AzureGlobalProperties.class, AzureGlobalProperties::new)
.withBean("customizer1", BlobServiceClientBuilderCustomizer.class, () -> customizer)
.withBean("customizer2", BlobServiceClientBuilderCustomizer.class, () -> customizer)
.run(context -> assertThat(customizer.getCustomizedTimes()).isEqualTo(2));
}
@Test
void otherCustomizerShouldNotBeCalled() {
BlobServiceClientBuilderCustomizer customizer = new BlobServiceClientBuilderCustomizer();
OtherBuilderCustomizer otherBuilderCustomizer = new OtherBuilderCustomizer();
this.contextRunner
.withPropertyValues("spring.cloud.azure.storage.blob.account-name=sa")
.withBean(AzureGlobalProperties.class, AzureGlobalProperties::new)
.withBean("customizer1", BlobServiceClientBuilderCustomizer.class, () -> customizer)
.withBean("customizer2", BlobServiceClientBuilderCustomizer.class, () -> customizer)
.withBean("customizer3", OtherBuilderCustomizer.class, () -> otherBuilderCustomizer)
.run(context -> {
assertThat(customizer.getCustomizedTimes()).isEqualTo(2);
assertThat(otherBuilderCustomizer.getCustomizedTimes()).isEqualTo(0);
});
}
@Test
private static class BlobServiceClientBuilderCustomizer extends TestBuilderCustomizer<BlobServiceClientBuilder> {
}
private static class OtherBuilderCustomizer extends TestBuilderCustomizer<ConfigurationClientBuilder> {
}
} |
`SimpleResponse` may be a better option here than `ResponseBase` #Resolved | Mono<Response<DownloadManifestResult>> downloadManifestWithResponse(String tagOrDigest, Context context) {
if (tagOrDigest == null) {
return monoError(logger, new NullPointerException("'tagOrDigest' can't be null."));
}
return this.registriesImpl.getManifestWithResponseAsync(repositoryName, tagOrDigest, UtilsImpl.OCI_MANIFEST_MEDIA_TYPE, context)
.flatMap(response -> {
String digest = response.getHeaders().getValue(UtilsImpl.DOCKER_DIGEST_HEADER_NAME);
ManifestWrapper wrapper = response.getValue();
if (Objects.equals(digest, tagOrDigest) || Objects.equals(response.getValue().getTag(), tagOrDigest)) {
OciManifest ociManifest = new OciManifest()
.setAnnotations(wrapper.getAnnotations())
.setConfig(wrapper.getConfig())
.setLayers(wrapper.getLayers())
.setSchemaVersion(wrapper.getSchemaVersion());
Response<DownloadManifestResult> res = new ResponseBase<Void, DownloadManifestResult>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
new DownloadManifestResult(digest, ociManifest, BinaryData.fromObject(ociManifest)),
null);
return Mono.just(res);
} else {
return monoError(logger, new ServiceResponseException("The digest in the response does not match the expected digest."));
}
}).onErrorMap(UtilsImpl::mapException);
} | Response<DownloadManifestResult> res = new ResponseBase<Void, DownloadManifestResult>( | return monoError(logger, new NullPointerException("'tagOrDigest' can't be null."));
}
return this.registriesImpl.getManifestWithResponseAsync(repositoryName, tagOrDigest, UtilsImpl.OCI_MANIFEST_MEDIA_TYPE, context)
.flatMap(response -> {
String digest = response.getHeaders().getValue(UtilsImpl.DOCKER_DIGEST_HEADER_NAME);
ManifestWrapper wrapper = response.getValue();
if (Objects.equals(digest, tagOrDigest) || Objects.equals(response.getValue().getTag(), tagOrDigest)) {
OciManifest ociManifest = new OciManifest()
.setAnnotations(wrapper.getAnnotations())
.setConfig(wrapper.getConfig())
.setLayers(wrapper.getLayers())
.setSchemaVersion(wrapper.getSchemaVersion());
Response<DownloadManifestResult> res = new SimpleResponse<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
new DownloadManifestResult(digest, ociManifest, BinaryData.fromObject(ociManifest)));
return Mono.just(res);
} else {
return monoError(logger, new ServiceResponseException("The digest in the response does not match the expected digest."));
}
} | class ContainerRegistryBlobAsyncClient {
private final AzureContainerRegistryImpl registryImplClient;
private final ContainerRegistryBlobsImpl blobsImpl;
private final ContainerRegistriesImpl registriesImpl;
private final String endpoint;
private final String repositoryName;
private final ClientLogger logger = new ClientLogger(ContainerRegistryBlobAsyncClient.class);
ContainerRegistryBlobAsyncClient(String repositoryName, HttpPipeline httpPipeline, String endpoint, String version) {
this.repositoryName = repositoryName;
this.endpoint = endpoint;
this.registryImplClient = new AzureContainerRegistryImplBuilder()
.url(endpoint)
.pipeline(httpPipeline)
.apiVersion(version)
.buildClient();
this.blobsImpl = this.registryImplClient.getContainerRegistryBlobs();
this.registriesImpl = this.registryImplClient.getContainerRegistries();
}
/**
* This method returns the registry's repository on which operations are being performed.
*
* @return The name of the repository
*/
public String getRepositoryName() {
return this.repositoryName;
}
/**
* This method returns the complete registry endpoint.
*
* @return The registry endpoint including the authority.
*/
public String getEndpoint() {
return this.endpoint;
}
/**
* Upload the Oci manifest to the repository.
* The upload is done as a single operation.
* @see <a href="https:
* @param manifest The OciManifest that needs to be uploaded.
* @return operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code manifest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadManifestResult> uploadManifest(OciManifest manifest) {
if (manifest == null) {
return monoError(logger, new NullPointerException("'manifest' can't be null."));
}
return uploadManifest(BinaryData.fromObject(manifest));
}
/**
* Upload the Oci manifest to the repository.
* The upload is done as a single operation.
* @see <a href="https:
* @param manifest The OciManifest that needs to be uploaded.
* @param options The options for the upload manifest operation.
* @return operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code manifest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadManifestResult> uploadManifest(OciManifest manifest, UploadManifestOptions options) {
if (manifest == null) {
return monoError(logger, new NullPointerException("'manifest' can't be null."));
}
return uploadManifest(BinaryData.fromObject(manifest), options);
}
/**
* Uploads a manifest to the repository.
* The client currently only supports uploading OciManifests to the repository.
* And this operation makes the assumption that the data provided is a valid OCI manifest.
* <p>
* Also, the data is read into memory and then an upload operation is performed as a single operation.
* @see <a href="https:
* @param data The manifest that needs to be uploaded.
* @return operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadManifestResult> uploadManifest(BinaryData data) {
if (data == null) {
return monoError(logger, new NullPointerException("'data' can't be null."));
}
return withContext(context -> this.uploadManifestWithResponse(data.toByteBuffer(), null, context)).flatMap(FluxUtil::toMono);
}
/**
* Uploads a manifest to the repository.
* The client currently only supports uploading OciManifests to the repository.
* And this operation makes the assumption that the data provided is a valid OCI manifest.
* <p>
* Also, the data is read into memory and then an upload operation is performed as a single operation.
* @see <a href="https:
* @param data The manifest that needs to be uploaded.
* @param options The options for the upload manifest operation.
* @return operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadManifestResult> uploadManifest(BinaryData data, UploadManifestOptions options) {
if (data == null) {
return monoError(logger, new NullPointerException("'data' can't be null."));
}
return withContext(context -> this.uploadManifestWithResponse(data.toByteBuffer(), options, context)).flatMap(FluxUtil::toMono);
}
/**
* Uploads a manifest to the repository.
* The client currently only supports uploading OciManifests to the repository.
* And this operation makes the assumption that the data provided is a valid OCI manifest.
* <p>
* Also, the data is read into memory and then an upload operation is performed as a single operation.
* @see <a href="https:
*
* @param data The manifest that needs to be uploaded.
* @param options The options for the upload manifest operation.
* @return The rest response containing the operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UploadManifestResult>> uploadManifestWithResponse(BinaryData data, UploadManifestOptions options) {
if (data == null) {
return monoError(logger, new NullPointerException("'data' can't be null."));
}
return withContext(context -> this.uploadManifestWithResponse(data.toByteBuffer(), options, context));
}
Mono<Response<UploadManifestResult>> uploadManifestWithResponse(ByteBuffer data, UploadManifestOptions options, Context context) {
if (data == null) {
return monoError(logger, new NullPointerException("'data' can't be null."));
}
String tagOrDigest = null;
if (options != null) {
tagOrDigest = options.getTag();
}
if (tagOrDigest == null) {
tagOrDigest = UtilsImpl.computeDigest(data);
}
return this.registriesImpl.createManifestWithResponseAsync(
repositoryName,
tagOrDigest,
Flux.just(data),
data.remaining(),
UtilsImpl.OCI_MANIFEST_MEDIA_TYPE,
context).map(response -> {
Response<UploadManifestResult> res = new ResponseBase<ContainerRegistriesCreateManifestHeaders, UploadManifestResult>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
new UploadManifestResult(response.getDeserializedHeaders().getDockerContentDigest()),
response.getDeserializedHeaders());
return res;
}).onErrorMap(UtilsImpl::mapException);
}
/**
* Uploads a blob to the repository.
* The client currently uploads the entire blob\layer as a single unit.
* <p>
* The blob is read into memory and then an upload operation is performed as a single operation.
* We currently do not support breaking the layer into multiple chunks and uploading them one at a time
*
* @param data The blob\image content that needs to be uploaded.
* @return The operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadBlobResult> uploadBlob(BinaryData data) {
if (data == null) {
return monoError(logger, new NullPointerException("'data' can't be null."));
}
return withContext(context -> this.uploadBlobWithResponse(data.toByteBuffer(), context)).flatMap(FluxUtil::toMono);
}
/**
* Uploads a blob to the repository.
* The client currently uploads the entire blob\layer as a single unit.
* <p>
* The blob is read into memory and then an upload operation is performed as a single operation.
* We currently do not support breaking the layer into multiple chunks and uploading them one at a time
*
* @param data The blob\image content that needs to be uploaded.
* @return The rest response containing the operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UploadBlobResult>> uploadBlobWithResponse(BinaryData data) {
return withContext(context -> this.uploadBlobWithResponse(data.toByteBuffer(), context));
}
Mono<Response<UploadBlobResult>> uploadBlobWithResponse(ByteBuffer data, Context context) {
if (data == null) {
return monoError(logger, new NullPointerException("'data' can't be null."));
}
String digest = UtilsImpl.computeDigest(data);
return this.blobsImpl.startUploadWithResponseAsync(repositoryName, context)
.flatMap(startUploadResponse -> this.blobsImpl.uploadChunkWithResponseAsync(trimNextLink(startUploadResponse.getDeserializedHeaders().getLocation()), Flux.just(data), data.remaining(), context))
.flatMap(uploadChunkResponse -> this.blobsImpl.completeUploadWithResponseAsync(digest, trimNextLink(uploadChunkResponse.getDeserializedHeaders().getLocation()), null, 0L, context))
.flatMap(completeUploadResponse -> {
Response<UploadBlobResult> res = new ResponseBase<ContainerRegistryBlobsCompleteUploadHeaders, UploadBlobResult>(completeUploadResponse.getRequest(),
completeUploadResponse.getStatusCode(),
completeUploadResponse.getHeaders(),
new UploadBlobResult(completeUploadResponse.getDeserializedHeaders().getDockerContentDigest()),
completeUploadResponse.getDeserializedHeaders());
return Mono.just(res);
}).onErrorMap(UtilsImpl::mapException);
}
private String trimNextLink(String locationHeader) {
if (locationHeader.startsWith("/")) {
return locationHeader.substring(1);
}
return locationHeader;
}
/**
* Download the manifest associated with the given tag or digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param tagOrDigest The tag or digest of the manifest.
* @return The manifest associated with the given tag or digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code tagOrDigest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DownloadManifestResult> downloadManifest(String tagOrDigest) {
return this.downloadManifestWithResponse(tagOrDigest).flatMap(FluxUtil::toMono);
}
/**
* Download the manifest associated with the given tag or digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param tagOrDigest The tag or digest of the manifest.
* @return The response for the manifest associated with the given tag or digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code tagOrDigest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DownloadManifestResult>> downloadManifestWithResponse(String tagOrDigest) {
return withContext(context -> this.downloadManifestWithResponse(tagOrDigest, context));
}
Mono<Response<DownloadManifestResult>> downloadManifestWithResponse(String tagOrDigest, Context context) {
if (tagOrDigest == null) {
).onErrorMap(UtilsImpl::mapException);
}
/**
* Download the blob associated with the given digest.
*
* @param digest The digest for the given image layer.
* @return The image associated with the given digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DownloadBlobResult> downloadBlob(String digest) {
return this.downloadBlobWithResponse(digest).flatMap(FluxUtil::toMono);
}
/**
* Download the blob\layer associated with the given digest.
*
* @param digest The digest for the given image layer.
* @return The image associated with the given digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DownloadBlobResult>> downloadBlobWithResponse(String digest) {
return withContext(context -> this.downloadBlobWithResponse(digest, context));
}
Mono<Response<DownloadBlobResult>> downloadBlobWithResponse(String digest, Context context) {
if (digest == null) {
return monoError(logger, new NullPointerException("'digest' can't be null."));
}
return this.blobsImpl.getBlobWithResponseAsync(repositoryName, digest, context).flatMap(streamResponse -> {
String resDigest = streamResponse.getHeaders().getValue(UtilsImpl.DOCKER_DIGEST_HEADER_NAME);
return BinaryData.fromFlux(streamResponse.getValue())
.flatMap(binaryData -> {
Response<DownloadBlobResult> response = new ResponseBase<HttpHeaders, DownloadBlobResult>(
streamResponse.getRequest(),
streamResponse.getStatusCode(),
streamResponse.getHeaders(),
new DownloadBlobResult(resDigest, binaryData),
null);
return Mono.just(response);
});
}).onErrorMap(UtilsImpl::mapException);
}
/**
* Delete the image associated with the given digest
*
* @param digest The digest for the given image layer.
* @return The completion signal.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteBlob(String digest) {
return this.deleteBlobWithResponse(digest).flatMap(FluxUtil::toMono);
}
/**
* Delete the image associated with the given digest
*
* @param digest The digest for the given image layer.
* @return The REST response for the completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteBlobWithResponse(String digest) {
return withContext(context -> deleteBlobWithResponse(digest, context));
}
Mono<Response<Void>> deleteBlobWithResponse(String digest, Context context) {
if (digest == null) {
return monoError(logger, new NullPointerException("'digest' can't be null."));
}
return this.blobsImpl.deleteBlobWithResponseAsync(repositoryName, digest, context)
.flatMap(UtilsImpl::deleteResponseToSuccess)
.onErrorMap(UtilsImpl::mapException);
}
/**
* Delete the manifest associated with the given digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param digest The digest of the manifest.
* @return The completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteManifest(String digest) {
return this.deleteManifestWithResponse(digest).flatMap(FluxUtil::toMono);
}
/**
* Delete the manifest associated with the given digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param digest The digest of the manifest.
* @return The REST response for completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteManifestWithResponse(String digest) {
return withContext(context -> deleteManifestWithResponse(digest, context));
}
Mono<Response<Void>> deleteManifestWithResponse(String digest, Context context) {
return this.registriesImpl.deleteManifestWithResponseAsync(repositoryName, digest, context)
.flatMap(UtilsImpl::deleteResponseToSuccess)
.onErrorMap(UtilsImpl::mapException);
}
} | class ContainerRegistryBlobAsyncClient {
private final AzureContainerRegistryImpl registryImplClient;
private final ContainerRegistryBlobsImpl blobsImpl;
private final ContainerRegistriesImpl registriesImpl;
private final String endpoint;
private final String repositoryName;
private final ClientLogger logger = new ClientLogger(ContainerRegistryBlobAsyncClient.class);
ContainerRegistryBlobAsyncClient(String repositoryName, HttpPipeline httpPipeline, String endpoint, String version) {
this.repositoryName = repositoryName;
this.endpoint = endpoint;
this.registryImplClient = new AzureContainerRegistryImplBuilder()
.url(endpoint)
.pipeline(httpPipeline)
.apiVersion(version)
.buildClient();
this.blobsImpl = this.registryImplClient.getContainerRegistryBlobs();
this.registriesImpl = this.registryImplClient.getContainerRegistries();
}
/**
* This method returns the registry's repository on which operations are being performed.
*
* @return The name of the repository
*/
public String getRepositoryName() {
return this.repositoryName;
}
/**
* This method returns the complete registry endpoint.
*
* @return The registry endpoint including the authority.
*/
public String getEndpoint() {
return this.endpoint;
}
/**
* Upload the Oci manifest to the repository.
* The upload is done as a single operation.
* @see <a href="https:
* @param manifest The OciManifest that needs to be uploaded.
* @return operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code manifest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadManifestResult> uploadManifest(OciManifest manifest) {
if (manifest == null) {
return monoError(logger, new NullPointerException("'manifest' can't be null."));
}
return withContext(context -> this.uploadManifestWithResponse(new UploadManifestOptions(manifest), context)).flatMap(FluxUtil::toMono);
}
/**
* Uploads a manifest to the repository.
* The client currently only supports uploading OciManifests to the repository.
* And this operation makes the assumption that the data provided is a valid OCI manifest.
* <p>
* Also, the data is read into memory and then an upload operation is performed as a single operation.
* @see <a href="https:
* @param options The options for the upload manifest operation.
* @return operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadManifestResult> uploadManifest(UploadManifestOptions options) {
if (options == null) {
return monoError(logger, new NullPointerException("'options' can't be null."));
}
return withContext(context -> this.uploadManifestWithResponse(options, context)).flatMap(FluxUtil::toMono);
}
/**
* Uploads a manifest to the repository.
* The client currently only supports uploading OciManifests to the repository.
* And this operation makes the assumption that the data provided is a valid OCI manifest.
* <p>
* Also, the data is read into memory and then an upload operation is performed as a single operation.
* @see <a href="https:
*
* @param options The options for the upload manifest operation.
* @return The rest response containing the operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UploadManifestResult>> uploadManifestWithResponse(UploadManifestOptions options) {
if (options == null) {
return monoError(logger, new NullPointerException("'options' can't be null."));
}
return withContext(context -> this.uploadManifestWithResponse(options, context));
}
Mono<Response<UploadManifestResult>> uploadManifestWithResponse(UploadManifestOptions options, Context context) {
if (options == null) {
return monoError(logger, new NullPointerException("'options' can't be null."));
}
ByteBuffer data = options.getManifest().toByteBuffer();
String tagOrDigest = options.getTag() != null ? options.getTag() : UtilsImpl.computeDigest(data);
return this.registriesImpl.createManifestWithResponseAsync(
repositoryName,
tagOrDigest,
Flux.just(data),
data.remaining(),
UtilsImpl.OCI_MANIFEST_MEDIA_TYPE,
context).map(response -> {
Response<UploadManifestResult> res = new ResponseBase<ContainerRegistriesCreateManifestHeaders, UploadManifestResult>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
new UploadManifestResult(response.getDeserializedHeaders().getDockerContentDigest()),
response.getDeserializedHeaders());
return res;
}).onErrorMap(UtilsImpl::mapException);
}
/**
* Uploads a blob to the repository.
* The client currently uploads the entire blob\layer as a single unit.
* <p>
* The blob is read into memory and then an upload operation is performed as a single operation.
* We currently do not support breaking the layer into multiple chunks and uploading them one at a time
*
* @param data The blob\image content that needs to be uploaded.
* @return The operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadBlobResult> uploadBlob(BinaryData data) {
if (data == null) {
return monoError(logger, new NullPointerException("'data' can't be null."));
}
return withContext(context -> this.uploadBlobWithResponse(data.toByteBuffer(), context)).flatMap(FluxUtil::toMono);
}
/**
* Uploads a blob to the repository.
* The client currently uploads the entire blob\layer as a single unit.
* <p>
* The blob is read into memory and then an upload operation is performed as a single operation.
* We currently do not support breaking the layer into multiple chunks and uploading them one at a time
*
* @param data The blob\image content that needs to be uploaded.
* @return The rest response containing the operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UploadBlobResult>> uploadBlobWithResponse(BinaryData data) {
return withContext(context -> this.uploadBlobWithResponse(data.toByteBuffer(), context));
}
Mono<Response<UploadBlobResult>> uploadBlobWithResponse(ByteBuffer data, Context context) {
if (data == null) {
return monoError(logger, new NullPointerException("'data' can't be null."));
}
String digest = UtilsImpl.computeDigest(data);
return this.blobsImpl.startUploadWithResponseAsync(repositoryName, context)
.flatMap(startUploadResponse -> this.blobsImpl.uploadChunkWithResponseAsync(trimNextLink(startUploadResponse.getDeserializedHeaders().getLocation()), Flux.just(data), data.remaining(), context))
.flatMap(uploadChunkResponse -> this.blobsImpl.completeUploadWithResponseAsync(digest, trimNextLink(uploadChunkResponse.getDeserializedHeaders().getLocation()), null, 0L, context))
.flatMap(completeUploadResponse -> {
Response<UploadBlobResult> res = new ResponseBase<ContainerRegistryBlobsCompleteUploadHeaders, UploadBlobResult>(completeUploadResponse.getRequest(),
completeUploadResponse.getStatusCode(),
completeUploadResponse.getHeaders(),
new UploadBlobResult(completeUploadResponse.getDeserializedHeaders().getDockerContentDigest()),
completeUploadResponse.getDeserializedHeaders());
return Mono.just(res);
}).onErrorMap(UtilsImpl::mapException);
}
private String trimNextLink(String locationHeader) {
if (locationHeader.startsWith("/")) {
return locationHeader.substring(1);
}
return locationHeader;
}
/**
* Download the manifest associated with the given tag or digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param tagOrDigest The tag or digest of the manifest.
* @return The manifest associated with the given tag or digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code tagOrDigest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DownloadManifestResult> downloadManifest(String tagOrDigest) {
return this.downloadManifestWithResponse(tagOrDigest).flatMap(FluxUtil::toMono);
}
/**
* Download the manifest associated with the given tag or digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param tagOrDigest The tag or digest of the manifest.
* @return The response for the manifest associated with the given tag or digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code tagOrDigest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DownloadManifestResult>> downloadManifestWithResponse(String tagOrDigest) {
return withContext(context -> this.downloadManifestWithResponse(tagOrDigest, context));
}
Mono<Response<DownloadManifestResult>> downloadManifestWithResponse(String tagOrDigest, Context context) {
if (tagOrDigest == null) {
).onErrorMap(UtilsImpl::mapException);
}
/**
* Download the blob associated with the given digest.
*
* @param digest The digest for the given image layer.
* @return The image associated with the given digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DownloadBlobResult> downloadBlob(String digest) {
return this.downloadBlobWithResponse(digest).flatMap(FluxUtil::toMono);
}
/**
* Download the blob\layer associated with the given digest.
*
* @param digest The digest for the given image layer.
* @return The image associated with the given digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DownloadBlobResult>> downloadBlobWithResponse(String digest) {
return withContext(context -> this.downloadBlobWithResponse(digest, context));
}
Mono<Response<DownloadBlobResult>> downloadBlobWithResponse(String digest, Context context) {
if (digest == null) {
return monoError(logger, new NullPointerException("'digest' can't be null."));
}
return this.blobsImpl.getBlobWithResponseAsync(repositoryName, digest, context).flatMap(streamResponse -> {
String resDigest = streamResponse.getHeaders().getValue(UtilsImpl.DOCKER_DIGEST_HEADER_NAME);
return BinaryData.fromFlux(streamResponse.getValue())
.flatMap(binaryData -> {
Response<DownloadBlobResult> response = new SimpleResponse<>(
streamResponse.getRequest(),
streamResponse.getStatusCode(),
streamResponse.getHeaders(),
new DownloadBlobResult(resDigest, binaryData));
return Mono.just(response);
});
}).onErrorMap(UtilsImpl::mapException);
}
/**
* Delete the image associated with the given digest
*
* @param digest The digest for the given image layer.
* @return The completion signal.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteBlob(String digest) {
return this.deleteBlobWithResponse(digest).flatMap(FluxUtil::toMono);
}
/**
* Delete the image associated with the given digest
*
* @param digest The digest for the given image layer.
* @return The REST response for the completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteBlobWithResponse(String digest) {
return withContext(context -> deleteBlobWithResponse(digest, context));
}
Mono<Response<Void>> deleteBlobWithResponse(String digest, Context context) {
if (digest == null) {
return monoError(logger, new NullPointerException("'digest' can't be null."));
}
return this.blobsImpl.deleteBlobWithResponseAsync(repositoryName, digest, context)
.flatMap(UtilsImpl::deleteResponseToSuccess)
.onErrorMap(UtilsImpl::mapException);
}
/**
* Delete the manifest associated with the given digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param digest The digest of the manifest.
* @return The completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteManifest(String digest) {
return this.deleteManifestWithResponse(digest).flatMap(FluxUtil::toMono);
}
/**
* Delete the manifest associated with the given digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param digest The digest of the manifest.
* @return The REST response for completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteManifestWithResponse(String digest) {
return withContext(context -> deleteManifestWithResponse(digest, context));
}
Mono<Response<Void>> deleteManifestWithResponse(String digest, Context context) {
return this.registriesImpl.deleteManifestWithResponseAsync(repositoryName, digest, context)
.flatMap(UtilsImpl::deleteResponseToSuccess)
.onErrorMap(UtilsImpl::mapException);
}
} |
Not sure I understand why? Once constructed it is already immutable and we do not want to be doing any decoding under the hood - no? | private static String byteArrayToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
} | return new String(hexChars); | private static String byteArrayToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
} | class UtilsImpl {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
private static final int HTTP_STATUS_CODE_NOT_FOUND;
private static final int HTTP_STATUS_CODE_ACCEPTED;
private static final String CONTINUATION_LINK_HEADER_NAME;
private static final Pattern CONTINUATION_LINK_PATTERN;
public static final String OCI_MANIFEST_MEDIA_TYPE;
public static final String DOCKER_DIGEST_HEADER_NAME;
public static final String CONTAINER_REGISTRY_TRACING_NAMESPACE_VALUE;
private static final ClientLogger LOGGER;
static {
LOGGER = new ClientLogger(UtilsImpl.class);
Map<String, String> properties = CoreUtils.getProperties("azure-containers-containerregistry.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
HTTP_STATUS_CODE_NOT_FOUND = 404;
HTTP_STATUS_CODE_ACCEPTED = 202;
OCI_MANIFEST_MEDIA_TYPE = "application/vnd.oci.image.manifest.v1+json";
DOCKER_DIGEST_HEADER_NAME = "Docker-Content-Digest";
CONTINUATION_LINK_HEADER_NAME = "Link";
CONTINUATION_LINK_PATTERN = Pattern.compile("<(.+)>;.*");
CONTAINER_REGISTRY_TRACING_NAMESPACE_VALUE = "Microsoft.ContainerRegistry";
}
private UtilsImpl() { }
/**
* This method builds the httpPipeline for the builders.
* @param clientOptions The client options
* @param logOptions http log options.
* @param configuration configuration settings.
* @param retryPolicy retry policy
* @param retryOptions retry options
* @param credential credentials.
* @param perCallPolicies per call policies.
* @param perRetryPolicies per retry policies.
* @param httpClient http client
* @param endpoint endpoint to be called
* @param serviceVersion the service api version being targeted by the client.
* @return returns the httpPipeline to be consumed by the builders.
*/
public static HttpPipeline buildHttpPipeline(
ClientOptions clientOptions,
HttpLogOptions logOptions,
Configuration configuration,
RetryPolicy retryPolicy,
RetryOptions retryOptions,
TokenCredential credential,
ContainerRegistryAudience audience,
List<HttpPipelinePolicy> perCallPolicies,
List<HttpPipelinePolicy> perRetryPolicies,
HttpClient httpClient,
String endpoint,
ContainerRegistryServiceVersion serviceVersion,
ClientLogger logger) {
ArrayList<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(
new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, logOptions), CLIENT_NAME, CLIENT_VERSION, configuration));
policies.add(new RequestIdPolicy());
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions));
policies.add(new CookiePolicy());
policies.add(new AddDatePolicy());
policies.addAll(perRetryPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
HttpLoggingPolicy loggingPolicy = new HttpLoggingPolicy(logOptions);
if (credential == null) {
logger.verbose("Credentials are null, enabling anonymous access");
}
ArrayList<HttpPipelinePolicy> credentialPolicies = clone(policies);
credentialPolicies.add(loggingPolicy);
if (audience == null) {
audience = ContainerRegistryAudience.AZURE_RESOURCE_MANAGER_PUBLIC_CLOUD;
}
ContainerRegistryTokenService tokenService = new ContainerRegistryTokenService(
credential,
audience,
endpoint,
serviceVersion,
new HttpPipelineBuilder()
.policies(credentialPolicies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build(),
JacksonAdapter.createDefaultSerializerAdapter());
ContainerRegistryCredentialsPolicy credentialsPolicy = new ContainerRegistryCredentialsPolicy(tokenService);
policies.add(credentialsPolicy);
policies.add(loggingPolicy);
HttpPipeline httpPipeline =
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return httpPipeline;
}
private static ArrayList<HttpPipelinePolicy> clone(ArrayList<HttpPipelinePolicy> policies) {
ArrayList<HttpPipelinePolicy> clonedPolicy = new ArrayList<>();
for (HttpPipelinePolicy policy:policies) {
clonedPolicy.add(policy);
}
return clonedPolicy;
}
/**
* This method computes the digest for the buffer content.
* Docker digest is a SHA256 hash of the docker image content and is deterministic based on the image build.
* @param buffer The buffer containing the image bytes.
* @return SHA-256 digest for the given buffer.
*/
public static String computeDigest(ByteBuffer buffer) {
ByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(readOnlyBuffer);
byte[] digest = md.digest();
return "sha256:" + byteArrayToHex(digest);
} catch (NoSuchAlgorithmException e) {
LOGGER.error("SHA-256 conversion failed with" + e.getMessage());
throw new RuntimeException(e);
}
}
private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();
/**
* Delete operation should be idempotent.
* And so should result in a success in case the service response is 400 : Not found.
* @param responseT The response object.
* @param <T> The encapsulating value.
* @return The transformed response object.
*/
public static <T> Mono<Response<Void>> deleteResponseToSuccess(Response<T> responseT) {
if (responseT.getStatusCode() != HTTP_STATUS_CODE_NOT_FOUND) {
return getAcceptedDeleteResponse(responseT, responseT.getStatusCode());
}
return getAcceptedDeleteResponse(responseT, HTTP_STATUS_CODE_ACCEPTED);
}
static <T> Mono<Response<Void>> getAcceptedDeleteResponse(Response<T> responseT, int statusCode) {
return Mono.just(new ResponseBase<String, Void>(
responseT.getRequest(),
statusCode,
responseT.getHeaders(),
null,
null));
}
/**
* This method converts the API response codes into well known exceptions.
* @param exception The exception returned by the rest client.
* @return The exception returned by the public methods.
*/
public static Throwable mapException(Throwable exception) {
AcrErrorsException acrException = null;
if (exception instanceof AcrErrorsException) {
acrException = ((AcrErrorsException) exception);
} else if (exception instanceof RuntimeException) {
RuntimeException runtimeException = (RuntimeException) exception;
Throwable throwable = runtimeException.getCause();
if (throwable instanceof AcrErrorsException) {
acrException = (AcrErrorsException) throwable;
}
}
if (acrException == null) {
return exception;
}
final HttpResponse errorHttpResponse = acrException.getResponse();
final int statusCode = errorHttpResponse.getStatusCode();
final String errorDetail = acrException.getMessage();
switch (statusCode) {
case 401:
return new ClientAuthenticationException(errorDetail, acrException.getResponse(), exception);
case 404:
return new ResourceNotFoundException(errorDetail, acrException.getResponse(), exception);
case 409:
return new ResourceExistsException(errorDetail, acrException.getResponse(), exception);
case 412:
return new ResourceModifiedException(errorDetail, acrException.getResponse(), exception);
default:
return new HttpResponseException(errorDetail, acrException.getResponse(), exception);
}
}
/**
* This method parses the response to get the continuation token used to make the next pagination call.
* The continuation token is returned by the service in the form of a header and not as a nextLink field.
* @param listResponse response that is parsed.
* @param <T> the model type that is being operated on.
* @return paged response with the correct continuation token.
*/
public static <T> PagedResponse<T> getPagedResponseWithContinuationToken(PagedResponse<T> listResponse) {
return getPagedResponseWithContinuationToken(listResponse, values -> values);
}
/**
* This method parses the response to get the continuation token used to make the next pagination call.
* The continuation token is returned by the service in the form of a header and not as a nextLink field.
*
* <p>
* Per the Docker v2 HTTP API spec, the Link header is an RFC5988
* compliant rel='next' with URL to next result set, if available.
* See: https:
*
* The URI reference can be obtained from link-value as follows:
* Link = "Link" ":"
* link-value = "<" URI-Reference ">" * (";" link-param )
* See: https:
* </p>
* @param listResponse response that is parsed.
* @param mapperFunction the function that maps the rest api response into the public model exposed by the client.
* @param <T> The model type returned by the rest client.
* @param <R> The model type returned by the public client.
* @return paged response with the correct continuation token.
*/
public static <T, R> PagedResponse<T> getPagedResponseWithContinuationToken(PagedResponse<R> listResponse, Function<List<R>, List<T>> mapperFunction) {
Objects.requireNonNull(mapperFunction);
String continuationLink = null;
HttpHeaders headers = listResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATION_LINK_HEADER_NAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Matcher matcher = CONTINUATION_LINK_PATTERN.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 1) {
continuationLink = matcher.group(1);
}
}
}
}
List<T> values = mapperFunction.apply(listResponse.getValue());
return new PagedResponseBase<String, T>(
listResponse.getRequest(),
listResponse.getStatusCode(),
listResponse.getHeaders(),
values,
continuationLink,
null
);
}
} | class UtilsImpl {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
private static final int HTTP_STATUS_CODE_NOT_FOUND;
private static final int HTTP_STATUS_CODE_ACCEPTED;
private static final String CONTINUATION_LINK_HEADER_NAME;
private static final Pattern CONTINUATION_LINK_PATTERN;
public static final String OCI_MANIFEST_MEDIA_TYPE;
public static final String DOCKER_DIGEST_HEADER_NAME;
public static final String CONTAINER_REGISTRY_TRACING_NAMESPACE_VALUE;
private static final ClientLogger LOGGER;
static {
LOGGER = new ClientLogger(UtilsImpl.class);
Map<String, String> properties = CoreUtils.getProperties("azure-containers-containerregistry.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
HTTP_STATUS_CODE_NOT_FOUND = 404;
HTTP_STATUS_CODE_ACCEPTED = 202;
OCI_MANIFEST_MEDIA_TYPE = "application/vnd.oci.image.manifest.v1+json";
DOCKER_DIGEST_HEADER_NAME = "Docker-Content-Digest";
CONTINUATION_LINK_HEADER_NAME = "Link";
CONTINUATION_LINK_PATTERN = Pattern.compile("<(.+)>;.*");
CONTAINER_REGISTRY_TRACING_NAMESPACE_VALUE = "Microsoft.ContainerRegistry";
}
private UtilsImpl() { }
/**
* This method builds the httpPipeline for the builders.
* @param clientOptions The client options
* @param logOptions http log options.
* @param configuration configuration settings.
* @param retryPolicy retry policy
* @param retryOptions retry options
* @param credential credentials.
* @param perCallPolicies per call policies.
* @param perRetryPolicies per retry policies.
* @param httpClient http client
* @param endpoint endpoint to be called
* @param serviceVersion the service api version being targeted by the client.
* @return returns the httpPipeline to be consumed by the builders.
*/
public static HttpPipeline buildHttpPipeline(
ClientOptions clientOptions,
HttpLogOptions logOptions,
Configuration configuration,
RetryPolicy retryPolicy,
RetryOptions retryOptions,
TokenCredential credential,
ContainerRegistryAudience audience,
List<HttpPipelinePolicy> perCallPolicies,
List<HttpPipelinePolicy> perRetryPolicies,
HttpClient httpClient,
String endpoint,
ContainerRegistryServiceVersion serviceVersion,
ClientLogger logger) {
ArrayList<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(
new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, logOptions), CLIENT_NAME, CLIENT_VERSION, configuration));
policies.add(new RequestIdPolicy());
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions));
policies.add(new CookiePolicy());
policies.add(new AddDatePolicy());
policies.addAll(perRetryPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
HttpLoggingPolicy loggingPolicy = new HttpLoggingPolicy(logOptions);
if (credential == null) {
logger.verbose("Credentials are null, enabling anonymous access");
}
ArrayList<HttpPipelinePolicy> credentialPolicies = clone(policies);
credentialPolicies.add(loggingPolicy);
if (audience == null) {
audience = ContainerRegistryAudience.AZURE_RESOURCE_MANAGER_PUBLIC_CLOUD;
}
ContainerRegistryTokenService tokenService = new ContainerRegistryTokenService(
credential,
audience,
endpoint,
serviceVersion,
new HttpPipelineBuilder()
.policies(credentialPolicies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build(),
JacksonAdapter.createDefaultSerializerAdapter());
ContainerRegistryCredentialsPolicy credentialsPolicy = new ContainerRegistryCredentialsPolicy(tokenService);
policies.add(credentialsPolicy);
policies.add(loggingPolicy);
HttpPipeline httpPipeline =
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return httpPipeline;
}
private static ArrayList<HttpPipelinePolicy> clone(ArrayList<HttpPipelinePolicy> policies) {
ArrayList<HttpPipelinePolicy> clonedPolicy = new ArrayList<>();
for (HttpPipelinePolicy policy:policies) {
clonedPolicy.add(policy);
}
return clonedPolicy;
}
/**
* This method computes the digest for the buffer content.
* Docker digest is a SHA256 hash of the docker image content and is deterministic based on the image build.
* @param buffer The buffer containing the image bytes.
* @return SHA-256 digest for the given buffer.
*/
public static String computeDigest(ByteBuffer buffer) {
ByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(readOnlyBuffer);
byte[] digest = md.digest();
return "sha256:" + byteArrayToHex(digest);
} catch (NoSuchAlgorithmException e) {
LOGGER.error("SHA-256 conversion failed with" + e);
throw new RuntimeException(e);
}
}
private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();
/**
* Delete operation should be idempotent.
* And so should result in a success in case the service response is 400 : Not found.
* @param responseT The response object.
* @param <T> The encapsulating value.
* @return The transformed response object.
*/
public static <T> Mono<Response<Void>> deleteResponseToSuccess(Response<T> responseT) {
if (responseT.getStatusCode() != HTTP_STATUS_CODE_NOT_FOUND) {
return getAcceptedDeleteResponse(responseT, responseT.getStatusCode());
}
return getAcceptedDeleteResponse(responseT, HTTP_STATUS_CODE_ACCEPTED);
}
static <T> Mono<Response<Void>> getAcceptedDeleteResponse(Response<T> responseT, int statusCode) {
return Mono.just(new SimpleResponse<Void>(
responseT.getRequest(),
statusCode,
responseT.getHeaders(),
null));
}
/**
* This method converts the API response codes into well known exceptions.
* @param exception The exception returned by the rest client.
* @return The exception returned by the public methods.
*/
public static Throwable mapException(Throwable exception) {
AcrErrorsException acrException = null;
if (exception instanceof AcrErrorsException) {
acrException = ((AcrErrorsException) exception);
} else if (exception instanceof RuntimeException) {
RuntimeException runtimeException = (RuntimeException) exception;
Throwable throwable = runtimeException.getCause();
if (throwable instanceof AcrErrorsException) {
acrException = (AcrErrorsException) throwable;
}
}
if (acrException == null) {
return exception;
}
final HttpResponse errorHttpResponse = acrException.getResponse();
final int statusCode = errorHttpResponse.getStatusCode();
final String errorDetail = acrException.getMessage();
switch (statusCode) {
case 401:
return new ClientAuthenticationException(errorDetail, acrException.getResponse(), exception);
case 404:
return new ResourceNotFoundException(errorDetail, acrException.getResponse(), exception);
case 409:
return new ResourceExistsException(errorDetail, acrException.getResponse(), exception);
case 412:
return new ResourceModifiedException(errorDetail, acrException.getResponse(), exception);
default:
return new HttpResponseException(errorDetail, acrException.getResponse(), exception);
}
}
/**
* This method parses the response to get the continuation token used to make the next pagination call.
* The continuation token is returned by the service in the form of a header and not as a nextLink field.
* @param listResponse response that is parsed.
* @param <T> the model type that is being operated on.
* @return paged response with the correct continuation token.
*/
public static <T> PagedResponse<T> getPagedResponseWithContinuationToken(PagedResponse<T> listResponse) {
return getPagedResponseWithContinuationToken(listResponse, values -> values);
}
/**
* This method parses the response to get the continuation token used to make the next pagination call.
* The continuation token is returned by the service in the form of a header and not as a nextLink field.
*
* <p>
* Per the Docker v2 HTTP API spec, the Link header is an RFC5988
* compliant rel='next' with URL to next result set, if available.
* See: https:
*
* The URI reference can be obtained from link-value as follows:
* Link = "Link" ":"
* link-value = "<" URI-Reference ">" * (";" link-param )
* See: https:
* </p>
* @param listResponse response that is parsed.
* @param mapperFunction the function that maps the rest api response into the public model exposed by the client.
* @param <T> The model type returned by the rest client.
* @param <R> The model type returned by the public client.
* @return paged response with the correct continuation token.
*/
public static <T, R> PagedResponse<T> getPagedResponseWithContinuationToken(PagedResponse<R> listResponse, Function<List<R>, List<T>> mapperFunction) {
Objects.requireNonNull(mapperFunction);
String continuationLink = null;
HttpHeaders headers = listResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATION_LINK_HEADER_NAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Matcher matcher = CONTINUATION_LINK_PATTERN.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 1) {
continuationLink = matcher.group(1);
}
}
}
}
List<T> values = mapperFunction.apply(listResponse.getValue());
return new PagedResponseBase<String, T>(
listResponse.getRequest(),
listResponse.getStatusCode(),
listResponse.getHeaders(),
values,
continuationLink,
null
);
}
} |
nit: Is this going to be commonly called? If so, can we use string concatenation instead of formatting as it is more readable and more performant (or at least should be). | public RequestResponseChannelClosedException(EndpointState sendLinkState, EndpointState receiveLinkState) {
super(String.format("Cannot send a message when request response channel is disposed. LinkState: (%s, %s)",
sendLinkState, receiveLinkState));
} | super(String.format("Cannot send a message when request response channel is disposed. LinkState: (%s, %s)", | public RequestResponseChannelClosedException(EndpointState sendLinkState, EndpointState receiveLinkState) {
super("Cannot send a message when request response channel is disposed. LinkState: (" + sendLinkState + "," + receiveLinkState + ")");
} | class RequestResponseChannelClosedException extends IllegalStateException {
public RequestResponseChannelClosedException() {
super("Cannot send a message when request response channel is disposed.");
}
} | class RequestResponseChannelClosedException extends IllegalStateException {
public RequestResponseChannelClosedException() {
super("Cannot send a message when request response channel is disposed.");
}
} |
sounds good, let's use concat. | public RequestResponseChannelClosedException(EndpointState sendLinkState, EndpointState receiveLinkState) {
super(String.format("Cannot send a message when request response channel is disposed. LinkState: (%s, %s)",
sendLinkState, receiveLinkState));
} | super(String.format("Cannot send a message when request response channel is disposed. LinkState: (%s, %s)", | public RequestResponseChannelClosedException(EndpointState sendLinkState, EndpointState receiveLinkState) {
super("Cannot send a message when request response channel is disposed. LinkState: (" + sendLinkState + "," + receiveLinkState + ")");
} | class RequestResponseChannelClosedException extends IllegalStateException {
public RequestResponseChannelClosedException() {
super("Cannot send a message when request response channel is disposed.");
}
} | class RequestResponseChannelClosedException extends IllegalStateException {
public RequestResponseChannelClosedException() {
super("Cannot send a message when request response channel is disposed.");
}
} |
I think the logic has been changed here when you replaced the shortened if by the `getHttpClient` function. | protected PhoneNumbersClientBuilder getClientBuilderUsingManagedIdentity(HttpClient httpClient) {
PhoneNumbersClientBuilder builder = new PhoneNumbersClientBuilder();
builder
.httpClient(getHttpClient(httpClient))
.addPolicy(getOverrideMSUseragentPolicy())
.endpoint(new CommunicationConnectionString(CONNECTION_STRING).getEndpoint());
if (getTestMode() == TestMode.PLAYBACK) {
builder.credential(new FakeCredentials());
} else {
builder.credential(new DefaultAzureCredentialBuilder().build());
}
if (shouldRecord()) {
builder.addPolicy(getRecordPolicy());
}
return builder;
} | builder.credential(new FakeCredentials()); | protected PhoneNumbersClientBuilder getClientBuilderUsingManagedIdentity(HttpClient httpClient) {
PhoneNumbersClientBuilder builder = new PhoneNumbersClientBuilder();
builder
.httpClient(getHttpClient(httpClient))
.addPolicy(getOverrideMSUserAgentPolicy())
.endpoint(new CommunicationConnectionString(CONNECTION_STRING).getEndpoint());
if (getTestMode() == TestMode.PLAYBACK) {
builder.credential(new FakeCredentials());
} else {
builder.credential(new DefaultAzureCredentialBuilder().build());
}
if (shouldRecord()) {
builder.addPolicy(getRecordPolicy());
}
return builder;
} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} |
Why not use MS_USERAGENT_OVERRIDE.isEmpty() ? | private HttpPipelinePolicy getOverrideMSUserAgentPolicy() {
HttpHeaders headers = new HttpHeaders();
if (!"".equals(MS_USERAGENT_OVERRIDE)) {
headers.add("x-ms-useragent", MS_USERAGENT_OVERRIDE);
}
return new AddHeadersPolicy(headers);
} | if (!"".equals(MS_USERAGENT_OVERRIDE)) { | private HttpPipelinePolicy getOverrideMSUserAgentPolicy() {
HttpHeaders headers = new HttpHeaders();
if (!MS_USERAGENT_OVERRIDE.isEmpty()) {
headers.add("x-ms-useragent", MS_USERAGENT_OVERRIDE);
}
return new AddHeadersPolicy(headers);
} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} |
I see that `getClientBuilderWithConnectionString` used to check if it is playback mode, while `getClientBuilderUsingManagedIdentity` checked for null; but neither checked for both. Is there any reason for generalizing on this? | private HttpClient getHttpClient(HttpClient httpClient) {
if (httpClient == null || getTestMode() == TestMode.PLAYBACK) {
return interceptorManager.getPlaybackClient();
}
return httpClient;
} | if (httpClient == null || getTestMode() == TestMode.PLAYBACK) { | private HttpClient getHttpClient(HttpClient httpClient) {
if (httpClient == null || getTestMode() == TestMode.PLAYBACK) {
return interceptorManager.getPlaybackClient();
}
return httpClient;
} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} |
Nice abstractions! | private HttpPipelinePolicy getRecordPolicy() {
List<Function<String, String>> redactors = new ArrayList<>();
redactors.add(data -> redact(data, JSON_PROPERTY_VALUE_REDACTION_PATTERN.matcher(data), "REDACTED"));
return interceptorManager.getRecordPolicy(redactors);
} | } | private HttpPipelinePolicy getRecordPolicy() {
List<Function<String, String>> redactors = new ArrayList<>();
redactors.add(data -> redact(data, JSON_PROPERTY_VALUE_REDACTION_PATTERN.matcher(data), "REDACTED"));
return interceptorManager.getRecordPolicy(redactors);
} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} |
I found [this](https://github.com/Azure/azure-sdk-for-java/blob/3f31d68eed6fbe11516ca3afe3955c8840a6e974/sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestBase.java#L151) method doc which implies that testing for null is the same as testing for playback mode | protected PhoneNumbersClientBuilder getClientBuilderUsingManagedIdentity(HttpClient httpClient) {
PhoneNumbersClientBuilder builder = new PhoneNumbersClientBuilder();
builder
.httpClient(getHttpClient(httpClient))
.addPolicy(getOverrideMSUseragentPolicy())
.endpoint(new CommunicationConnectionString(CONNECTION_STRING).getEndpoint());
if (getTestMode() == TestMode.PLAYBACK) {
builder.credential(new FakeCredentials());
} else {
builder.credential(new DefaultAzureCredentialBuilder().build());
}
if (shouldRecord()) {
builder.addPolicy(getRecordPolicy());
}
return builder;
} | builder.credential(new FakeCredentials()); | protected PhoneNumbersClientBuilder getClientBuilderUsingManagedIdentity(HttpClient httpClient) {
PhoneNumbersClientBuilder builder = new PhoneNumbersClientBuilder();
builder
.httpClient(getHttpClient(httpClient))
.addPolicy(getOverrideMSUserAgentPolicy())
.endpoint(new CommunicationConnectionString(CONNECTION_STRING).getEndpoint());
if (getTestMode() == TestMode.PLAYBACK) {
builder.credential(new FakeCredentials());
} else {
builder.credential(new DefaultAzureCredentialBuilder().build());
}
if (shouldRecord()) {
builder.addPolicy(getRecordPolicy());
}
return builder;
} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} |
Thank you! | private HttpPipelinePolicy getRecordPolicy() {
List<Function<String, String>> redactors = new ArrayList<>();
redactors.add(data -> redact(data, JSON_PROPERTY_VALUE_REDACTION_PATTERN.matcher(data), "REDACTED"));
return interceptorManager.getRecordPolicy(redactors);
} | } | private HttpPipelinePolicy getRecordPolicy() {
List<Function<String, String>> redactors = new ArrayList<>();
redactors.add(data -> redact(data, JSON_PROPERTY_VALUE_REDACTION_PATTERN.matcher(data), "REDACTED"));
return interceptorManager.getRecordPolicy(redactors);
} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} |
I'm trying to cover all cases, but it seems that testing for just one of them is enough, see my reply to @lucasrsant for my thought process | private HttpClient getHttpClient(HttpClient httpClient) {
if (httpClient == null || getTestMode() == TestMode.PLAYBACK) {
return interceptorManager.getPlaybackClient();
}
return httpClient;
} | if (httpClient == null || getTestMode() == TestMode.PLAYBACK) { | private HttpClient getHttpClient(HttpClient httpClient) {
if (httpClient == null || getTestMode() == TestMode.PLAYBACK) {
return interceptorManager.getPlaybackClient();
}
return httpClient;
} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} |
Is there any other reason why this function test this differently ? | protected PhoneNumbersClientBuilder getClientBuilderUsingManagedIdentity(HttpClient httpClient) {
PhoneNumbersClientBuilder builder = new PhoneNumbersClientBuilder();
builder
.httpClient(getHttpClient(httpClient))
.addPolicy(getOverrideMSUseragentPolicy())
.endpoint(new CommunicationConnectionString(CONNECTION_STRING).getEndpoint());
if (getTestMode() == TestMode.PLAYBACK) {
builder.credential(new FakeCredentials());
} else {
builder.credential(new DefaultAzureCredentialBuilder().build());
}
if (shouldRecord()) {
builder.addPolicy(getRecordPolicy());
}
return builder;
} | builder.credential(new FakeCredentials()); | protected PhoneNumbersClientBuilder getClientBuilderUsingManagedIdentity(HttpClient httpClient) {
PhoneNumbersClientBuilder builder = new PhoneNumbersClientBuilder();
builder
.httpClient(getHttpClient(httpClient))
.addPolicy(getOverrideMSUserAgentPolicy())
.endpoint(new CommunicationConnectionString(CONNECTION_STRING).getEndpoint());
if (getTestMode() == TestMode.PLAYBACK) {
builder.credential(new FakeCredentials());
} else {
builder.credential(new DefaultAzureCredentialBuilder().build());
}
if (shouldRecord()) {
builder.addPolicy(getRecordPolicy());
}
return builder;
} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} |
Is it guaranteed that when `httpClient` is not null, the TestMode is `PLAYBACK`? If so, this is fine, otherwise, it will lead to an unexpected behavior. | protected PhoneNumbersClientBuilder getClientBuilderUsingManagedIdentity(HttpClient httpClient) {
PhoneNumbersClientBuilder builder = new PhoneNumbersClientBuilder();
builder
.httpClient(getHttpClient(httpClient))
.addPolicy(getOverrideMSUseragentPolicy())
.endpoint(new CommunicationConnectionString(CONNECTION_STRING).getEndpoint());
if (getTestMode() == TestMode.PLAYBACK) {
builder.credential(new FakeCredentials());
} else {
builder.credential(new DefaultAzureCredentialBuilder().build());
}
if (shouldRecord()) {
builder.addPolicy(getRecordPolicy());
}
return builder;
} | builder.credential(new FakeCredentials()); | protected PhoneNumbersClientBuilder getClientBuilderUsingManagedIdentity(HttpClient httpClient) {
PhoneNumbersClientBuilder builder = new PhoneNumbersClientBuilder();
builder
.httpClient(getHttpClient(httpClient))
.addPolicy(getOverrideMSUserAgentPolicy())
.endpoint(new CommunicationConnectionString(CONNECTION_STRING).getEndpoint());
if (getTestMode() == TestMode.PLAYBACK) {
builder.credential(new FakeCredentials());
} else {
builder.credential(new DefaultAzureCredentialBuilder().build());
}
if (shouldRecord()) {
builder.addPolicy(getRecordPolicy());
}
return builder;
} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} |
Sure... I'll change it to smaller size. | public void canCreateVirtualMachineWithEphemeralOSDisk() {
VirtualMachine vm = computeManager.virtualMachines()
.define(vmName)
.withRegion(Region.US_WEST3)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.withSize(VirtualMachineSizeTypes.STANDARD_D8S_V3)
.withEphemeralOSDisk()
.withPlacement(DiffDiskPlacement.CACHE_DISK)
.withNewDataDisk(1, 1, CachingTypes.READ_WRITE)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.create();
Assertions.assertNull(vm.osDiskDiskEncryptionSetId());
Assertions.assertTrue(vm.osDiskSize() > 0);
Assertions.assertEquals(vm.osDiskDeleteOptions(), DeleteOptions.DELETE);
Assertions.assertEquals(vm.osDiskCachingType(), CachingTypes.READ_ONLY);
Assertions.assertFalse(CoreUtils.isNullOrEmpty(vm.dataDisks()));
Assertions.assertTrue(vm.osDiskIsEphemeral());
Assertions.assertNotNull(vm.osDiskId());
String osDiskId = vm.osDiskId();
vm.update()
.withoutDataDisk(1)
.withNewDataDisk(1, 2, CachingTypes.NONE)
.withNewDataDisk(1)
.apply();
Assertions.assertEquals(vm.dataDisks().size(), 2);
vm.powerOff();
vm.start();
vm.refresh();
Assertions.assertEquals(osDiskId, vm.osDiskId());
Assertions.assertThrows(Exception.class, vm::deallocate);
} | .withSize(VirtualMachineSizeTypes.STANDARD_D8S_V3) | public void canCreateVirtualMachineWithEphemeralOSDisk() {
VirtualMachine vm = computeManager.virtualMachines()
.define(vmName)
.withRegion(Region.US_WEST3)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2)
.withEphemeralOSDisk()
.withPlacement(DiffDiskPlacement.CACHE_DISK)
.withNewDataDisk(1, 1, CachingTypes.READ_WRITE)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.create();
Assertions.assertNull(vm.osDiskDiskEncryptionSetId());
Assertions.assertTrue(vm.osDiskSize() > 0);
Assertions.assertEquals(vm.osDiskDeleteOptions(), DeleteOptions.DELETE);
Assertions.assertEquals(vm.osDiskCachingType(), CachingTypes.READ_ONLY);
Assertions.assertFalse(CoreUtils.isNullOrEmpty(vm.dataDisks()));
Assertions.assertTrue(vm.isOSDiskEphemeral());
Assertions.assertNotNull(vm.osDiskId());
String osDiskId = vm.osDiskId();
vm.update()
.withoutDataDisk(1)
.withNewDataDisk(1, 2, CachingTypes.NONE)
.withNewDataDisk(1)
.apply();
Assertions.assertEquals(vm.dataDisks().size(), 2);
vm.powerOff();
vm.start();
vm.refresh();
Assertions.assertEquals(osDiskId, vm.osDiskId());
Assertions.assertThrows(Exception.class, vm::deallocate);
} | class VirtualMachineOperationsTests extends ComputeManagementTest {
private String rgName = "";
private String rgName2 = "";
private final Region region = Region.US_EAST;
private final Region regionProxPlacementGroup = Region.US_WEST;
private final Region regionProxPlacementGroup2 = Region.US_EAST;
private final String vmName = "javavm";
private final String proxGroupName = "testproxgroup1";
private final String proxGroupName2 = "testproxgroup2";
private final String availabilitySetName = "availset1";
private final String availabilitySetName2 = "availset2";
private final ProximityPlacementGroupType proxGroupType = ProximityPlacementGroupType.STANDARD;
@Override
protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) {
rgName = generateRandomResourceName("javacsmrg", 15);
rgName2 = generateRandomResourceName("javacsmrg2", 15);
super.initializeClients(httpPipeline, profile);
}
@Override
protected void cleanUpResources() {
if (rgName != null) {
resourceManager.resourceGroups().beginDeleteByName(rgName);
}
}
@Test
public void canCreateVirtualMachineWithNetworking() throws Exception {
NetworkSecurityGroup nsg =
this
.networkManager
.networkSecurityGroups()
.define("nsg")
.withRegion(region)
.withNewResourceGroup(rgName)
.defineRule("rule1")
.allowInbound()
.fromAnyAddress()
.fromPort(80)
.toAnyAddress()
.toPort(80)
.withProtocol(SecurityRuleProtocol.TCP)
.attach()
.create();
Creatable<Network> networkDefinition =
this
.networkManager
.networks()
.define("network1")
.withRegion(region)
.withNewResourceGroup(rgName)
.withAddressSpace("10.0.0.0/28")
.defineSubnet("subnet1")
.withAddressPrefix("10.0.0.0/29")
.withExistingNetworkSecurityGroup(nsg)
.attach();
VirtualMachine vm =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork(networkDefinition)
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.create();
NetworkInterface primaryNic = vm.getPrimaryNetworkInterface();
Assertions.assertNotNull(primaryNic);
NicIpConfiguration primaryIpConfig = primaryNic.primaryIPConfiguration();
Assertions.assertNotNull(primaryIpConfig);
Assertions.assertNotNull(primaryIpConfig.networkId());
Network network = primaryIpConfig.getNetwork();
Assertions.assertNotNull(primaryIpConfig.subnetName());
Subnet subnet = network.subnets().get(primaryIpConfig.subnetName());
Assertions.assertNotNull(subnet);
nsg = subnet.getNetworkSecurityGroup();
Assertions.assertNotNull(nsg);
Assertions.assertEquals("nsg", nsg.name());
Assertions.assertEquals(1, nsg.securityRules().size());
nsg = primaryIpConfig.getNetworkSecurityGroup();
Assertions.assertEquals("nsg", nsg.name());
}
@Test
public void canCreateVirtualMachine() throws Exception {
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLicenseType("Windows_Server")
.create();
VirtualMachine foundVM = null;
PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName);
for (VirtualMachine vm1 : vms) {
if (vm1.name().equals(vmName)) {
foundVM = vm1;
break;
}
}
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(region, foundVM.region());
foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(region, foundVM.region());
Assertions.assertEquals("Windows_Server", foundVM.licenseType());
PowerState powerState = foundVM.powerState();
Assertions.assertEquals(powerState, PowerState.RUNNING);
VirtualMachineInstanceView instanceView = foundVM.instanceView();
Assertions.assertNotNull(instanceView);
Assertions.assertNotNull(instanceView.statuses().size() > 0);
computeManager.virtualMachines().deleteById(foundVM.id());
}
@Test
public void cannotCreateVirtualMachineSyncPoll() throws Exception {
final String mySqlInstallScript = "https:
final String installCommand = "bash install_mysql_server_5.6.sh Abc.123x(";
Assertions.assertThrows(IllegalStateException.class, () -> {
Accepted<VirtualMachine> acceptedVirtualMachine =
this.computeManager.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.defineNewExtension("CustomScriptForLinux")
.withPublisher("Microsoft.OSTCExtensions")
.withType("CustomScriptForLinux")
.withVersion("1.4")
.withMinorVersionAutoUpgrade()
.withPublicSetting("fileUris", Collections.singletonList(mySqlInstallScript))
.withPublicSetting("commandToExecute", installCommand)
.attach()
.beginCreate();
});
boolean dependentResourceCreated = computeManager.resourceManager().serviceClient().getResourceGroups().checkExistence(rgName);
Assertions.assertFalse(dependentResourceCreated);
rgName = null;
}
@Test
public void canCreateVirtualMachineSyncPoll() throws Exception {
final long defaultDelayInMillis = 10 * 1000;
Accepted<VirtualMachine> acceptedVirtualMachine = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLicenseType("Windows_Server")
.beginCreate();
VirtualMachine createdVirtualMachine = acceptedVirtualMachine.getActivationResponse().getValue();
Assertions.assertNotEquals("Succeeded", createdVirtualMachine.provisioningState());
LongRunningOperationStatus pollStatus = acceptedVirtualMachine.getActivationResponse().getStatus();
long delayInMills = acceptedVirtualMachine.getActivationResponse().getRetryAfter() == null
? defaultDelayInMillis
: acceptedVirtualMachine.getActivationResponse().getRetryAfter().toMillis();
while (!pollStatus.isComplete()) {
ResourceManagerUtils.sleep(Duration.ofMillis(delayInMills));
PollResponse<?> pollResponse = acceptedVirtualMachine.getSyncPoller().poll();
pollStatus = pollResponse.getStatus();
delayInMills = pollResponse.getRetryAfter() == null
? defaultDelayInMillis
: pollResponse.getRetryAfter().toMillis();
}
Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollStatus);
VirtualMachine virtualMachine = acceptedVirtualMachine.getFinalResult();
Assertions.assertEquals("Succeeded", virtualMachine.provisioningState());
Accepted<Void> acceptedDelete = computeManager.virtualMachines()
.beginDeleteByResourceGroup(virtualMachine.resourceGroupName(), virtualMachine.name());
pollStatus = acceptedDelete.getActivationResponse().getStatus();
delayInMills = acceptedDelete.getActivationResponse().getRetryAfter() == null
? defaultDelayInMillis
: (int) acceptedDelete.getActivationResponse().getRetryAfter().toMillis();
while (!pollStatus.isComplete()) {
ResourceManagerUtils.sleep(Duration.ofMillis(delayInMills));
PollResponse<?> pollResponse = acceptedDelete.getSyncPoller().poll();
pollStatus = pollResponse.getStatus();
delayInMills = pollResponse.getRetryAfter() == null
? defaultDelayInMillis
: (int) pollResponse.getRetryAfter().toMillis();
}
boolean deleted = false;
try {
computeManager.virtualMachines().getById(virtualMachine.id());
} catch (ManagementException e) {
if (e.getResponse().getStatusCode() == 404
&& ("NotFound".equals(e.getValue().getCode()) || "ResourceNotFound".equals(e.getValue().getCode()))) {
deleted = true;
}
}
Assertions.assertTrue(deleted);
}
@Test
public void canCreateUpdatePriorityAndPrice() throws Exception {
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLowPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE)
.withMaxPrice(1000.0)
.withLicenseType("Windows_Server")
.create();
VirtualMachine foundVM = null;
PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName);
for (VirtualMachine vm1 : vms) {
if (vm1.name().equals(vmName)) {
foundVM = vm1;
break;
}
}
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(region, foundVM.region());
foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(region, foundVM.region());
Assertions.assertEquals("Windows_Server", foundVM.licenseType());
Assertions.assertEquals((Double) 1000.0, foundVM.billingProfile().maxPrice());
Assertions.assertEquals(VirtualMachineEvictionPolicyTypes.DEALLOCATE, foundVM.evictionPolicy());
try {
foundVM.update().withMaxPrice(1500.0).apply();
Assertions.assertEquals((Double) 1500.0, foundVM.billingProfile().maxPrice());
Assertions.fail();
} catch (ManagementException e) {
}
foundVM.deallocate();
foundVM.update().withMaxPrice(2000.0).apply();
foundVM.start();
Assertions.assertEquals((Double) 2000.0, foundVM.billingProfile().maxPrice());
foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.SPOT).apply();
Assertions.assertEquals(VirtualMachinePriorityTypes.SPOT, foundVM.priority());
foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.LOW).apply();
Assertions.assertEquals(VirtualMachinePriorityTypes.LOW, foundVM.priority());
try {
foundVM.update().withPriority(VirtualMachinePriorityTypes.REGULAR).apply();
Assertions.assertEquals(VirtualMachinePriorityTypes.REGULAR, foundVM.priority());
Assertions.fail();
} catch (ManagementException e) {
}
computeManager.virtualMachines().deleteById(foundVM.id());
}
@Test
public void cannotUpdateProximityPlacementGroupForVirtualMachine() throws Exception {
AvailabilitySet setCreated =
computeManager
.availabilitySets()
.define(availabilitySetName)
.withRegion(regionProxPlacementGroup)
.withNewResourceGroup(rgName)
.withNewProximityPlacementGroup(proxGroupName, proxGroupType)
.create();
Assertions.assertEquals(availabilitySetName, setCreated.name());
Assertions.assertNotNull(setCreated.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location());
AvailabilitySet setCreated2 =
computeManager
.availabilitySets()
.define(availabilitySetName2)
.withRegion(regionProxPlacementGroup2)
.withNewResourceGroup(rgName2)
.withNewProximityPlacementGroup(proxGroupName2, proxGroupType)
.create();
Assertions.assertEquals(availabilitySetName2, setCreated2.name());
Assertions.assertNotNull(setCreated2.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, setCreated2.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(setCreated2.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(setCreated2.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated2.id().equalsIgnoreCase(setCreated2.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertEquals(setCreated2.regionName(), setCreated2.proximityPlacementGroup().location());
computeManager
.virtualMachines()
.define(vmName)
.withRegion(regionProxPlacementGroup)
.withExistingResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withProximityPlacementGroup(setCreated.proximityPlacementGroup().id())
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLicenseType("Windows_Server")
.create();
VirtualMachine foundVM = null;
PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName);
for (VirtualMachine vm1 : vms) {
if (vm1.name().equals(vmName)) {
foundVM = vm1;
break;
}
}
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(regionProxPlacementGroup, foundVM.region());
foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(regionProxPlacementGroup, foundVM.region());
Assertions.assertEquals("Windows_Server", foundVM.licenseType());
PowerState powerState = foundVM.powerState();
Assertions.assertEquals(powerState, PowerState.RUNNING);
VirtualMachineInstanceView instanceView = foundVM.instanceView();
Assertions.assertNotNull(instanceView);
Assertions.assertNotNull(instanceView.statuses().size() > 0);
Assertions.assertNotNull(foundVM.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds());
Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty());
Assertions
.assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0)));
try {
VirtualMachine updatedVm =
foundVM.update().withProximityPlacementGroup(setCreated2.proximityPlacementGroup().id()).apply();
} catch (ManagementException clEx) {
Assertions
.assertTrue(
clEx
.getMessage()
.contains(
"Updating proximity placement group of VM javavm is not allowed while the VM is running."
+ " Please stop/deallocate the VM and retry the operation."));
}
computeManager.virtualMachines().deleteById(foundVM.id());
computeManager.availabilitySets().deleteById(setCreated.id());
}
@Test
public void canCreateVirtualMachinesAndAvailabilitySetInSameProximityPlacementGroup() throws Exception {
AvailabilitySet setCreated =
computeManager
.availabilitySets()
.define(availabilitySetName)
.withRegion(regionProxPlacementGroup)
.withNewResourceGroup(rgName)
.withNewProximityPlacementGroup(proxGroupName, proxGroupType)
.create();
Assertions.assertEquals(availabilitySetName, setCreated.name());
Assertions.assertNotNull(setCreated.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location());
computeManager
.virtualMachines()
.define(vmName)
.withRegion(regionProxPlacementGroup)
.withExistingResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withProximityPlacementGroup(setCreated.proximityPlacementGroup().id())
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLicenseType("Windows_Server")
.create();
VirtualMachine foundVM = null;
PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName);
for (VirtualMachine vm1 : vms) {
if (vm1.name().equals(vmName)) {
foundVM = vm1;
break;
}
}
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(regionProxPlacementGroup, foundVM.region());
foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(regionProxPlacementGroup, foundVM.region());
Assertions.assertEquals("Windows_Server", foundVM.licenseType());
PowerState powerState = foundVM.powerState();
Assertions.assertEquals(powerState, PowerState.RUNNING);
VirtualMachineInstanceView instanceView = foundVM.instanceView();
Assertions.assertNotNull(instanceView);
Assertions.assertNotNull(instanceView.statuses().size() > 0);
Assertions.assertNotNull(foundVM.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds());
Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty());
Assertions
.assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0)));
VirtualMachine updatedVm = foundVM.update().withoutProximityPlacementGroup().apply();
Assertions.assertNotNull(updatedVm.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, updatedVm.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(updatedVm.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(updatedVm.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(updatedVm.proximityPlacementGroup().availabilitySetIds().get(0)));
computeManager.virtualMachines().deleteById(foundVM.id());
computeManager.availabilitySets().deleteById(setCreated.id());
}
@Test
public void canCreateVirtualMachinesAndRelatedResourcesInParallel() throws Exception {
String vmNamePrefix = "vmz";
String publicIpNamePrefix = generateRandomResourceName("pip-", 15);
String networkNamePrefix = generateRandomResourceName("vnet-", 15);
int count = 5;
CreatablesInfo creatablesInfo =
prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count);
List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables;
List<String> networkCreatableKeys = creatablesInfo.networkCreatableKeys;
List<String> publicIpCreatableKeys = creatablesInfo.publicIpCreatableKeys;
CreatedResources<VirtualMachine> createdVirtualMachines =
computeManager.virtualMachines().create(virtualMachineCreatables);
Assertions.assertTrue(createdVirtualMachines.size() == count);
Set<String> virtualMachineNames = new HashSet<>();
for (int i = 0; i < count; i++) {
virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i));
}
for (VirtualMachine virtualMachine : createdVirtualMachines.values()) {
Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name()));
Assertions.assertNotNull(virtualMachine.id());
}
Set<String> networkNames = new HashSet<>();
for (int i = 0; i < count; i++) {
networkNames.add(String.format("%s-%d", networkNamePrefix, i));
}
for (String networkCreatableKey : networkCreatableKeys) {
Network createdNetwork = (Network) createdVirtualMachines.createdRelatedResource(networkCreatableKey);
Assertions.assertNotNull(createdNetwork);
Assertions.assertTrue(networkNames.contains(createdNetwork.name()));
}
Set<String> publicIPAddressNames = new HashSet<>();
for (int i = 0; i < count; i++) {
publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i));
}
for (String publicIpCreatableKey : publicIpCreatableKeys) {
PublicIpAddress createdPublicIpAddress =
(PublicIpAddress) createdVirtualMachines.createdRelatedResource(publicIpCreatableKey);
Assertions.assertNotNull(createdPublicIpAddress);
Assertions.assertTrue(publicIPAddressNames.contains(createdPublicIpAddress.name()));
}
}
@Test
public void canStreamParallelCreatedVirtualMachinesAndRelatedResources() throws Exception {
String vmNamePrefix = "vmz";
String publicIpNamePrefix = generateRandomResourceName("pip-", 15);
String networkNamePrefix = generateRandomResourceName("vnet-", 15);
int count = 5;
final Set<String> virtualMachineNames = new HashSet<>();
for (int i = 0; i < count; i++) {
virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i));
}
final Set<String> networkNames = new HashSet<>();
for (int i = 0; i < count; i++) {
networkNames.add(String.format("%s-%d", networkNamePrefix, i));
}
final Set<String> publicIPAddressNames = new HashSet<>();
for (int i = 0; i < count; i++) {
publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i));
}
final CreatablesInfo creatablesInfo =
prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count);
final AtomicInteger resourceCount = new AtomicInteger(0);
List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables;
computeManager
.virtualMachines()
.createAsync(virtualMachineCreatables)
.map(
createdResource -> {
if (createdResource instanceof Resource) {
Resource resource = (Resource) createdResource;
System.out.println("Created: " + resource.id());
if (resource instanceof VirtualMachine) {
VirtualMachine virtualMachine = (VirtualMachine) resource;
Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name()));
Assertions.assertNotNull(virtualMachine.id());
} else if (resource instanceof Network) {
Network network = (Network) resource;
Assertions.assertTrue(networkNames.contains(network.name()));
Assertions.assertNotNull(network.id());
} else if (resource instanceof PublicIpAddress) {
PublicIpAddress publicIPAddress = (PublicIpAddress) resource;
Assertions.assertTrue(publicIPAddressNames.contains(publicIPAddress.name()));
Assertions.assertNotNull(publicIPAddress.id());
}
}
resourceCount.incrementAndGet();
return createdResource;
})
.blockLast();
networkNames.forEach(name -> {
Assertions.assertNotNull(networkManager.networks().getByResourceGroup(rgName, name));
});
publicIPAddressNames.forEach(name -> {
Assertions.assertNotNull(networkManager.publicIpAddresses().getByResourceGroup(rgName, name));
});
Assertions.assertEquals(1, storageManager.storageAccounts().listByResourceGroup(rgName).stream().count());
Assertions.assertEquals(count, networkManager.networkInterfaces().listByResourceGroup(rgName).stream().count());
Assertions.assertEquals(count, resourceCount.get());
}
@Test
public void canSetStorageAccountForUnmanagedDisk() {
final String storageName = generateRandomResourceName("st", 14);
StorageAccount storageAccount =
storageManager
.storageAccounts()
.define(storageName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withSku(StorageAccountSkuType.PREMIUM_LRS)
.create();
VirtualMachine virtualMachine =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.withUnmanagedDisks()
.defineUnmanagedDataDisk("disk1")
.withNewVhd(100)
.withLun(2)
.storeAt(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd")
.attach()
.defineUnmanagedDataDisk("disk2")
.withNewVhd(100)
.withLun(3)
.storeAt(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd")
.attach()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.create();
Map<Integer, VirtualMachineUnmanagedDataDisk> unmanagedDataDisks = virtualMachine.unmanagedDataDisks();
Assertions.assertNotNull(unmanagedDataDisks);
Assertions.assertEquals(2, unmanagedDataDisks.size());
VirtualMachineUnmanagedDataDisk firstUnmanagedDataDisk = unmanagedDataDisks.get(2);
Assertions.assertNotNull(firstUnmanagedDataDisk);
VirtualMachineUnmanagedDataDisk secondUnmanagedDataDisk = unmanagedDataDisks.get(3);
Assertions.assertNotNull(secondUnmanagedDataDisk);
String createdVhdUri1 = firstUnmanagedDataDisk.vhdUri();
String createdVhdUri2 = secondUnmanagedDataDisk.vhdUri();
Assertions.assertNotNull(createdVhdUri1);
Assertions.assertNotNull(createdVhdUri2);
computeManager.virtualMachines().deleteById(virtualMachine.id());
virtualMachine =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.withUnmanagedDisks()
.withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd")
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4"))
.create();
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
unmanagedDataDisks = virtualMachine.unmanagedDataDisks();
Assertions.assertNotNull(unmanagedDataDisks);
Assertions.assertEquals(1, unmanagedDataDisks.size());
firstUnmanagedDataDisk = null;
for (VirtualMachineUnmanagedDataDisk unmanagedDisk : unmanagedDataDisks.values()) {
firstUnmanagedDataDisk = unmanagedDisk;
break;
}
Assertions.assertNotNull(firstUnmanagedDataDisk.vhdUri());
Assertions.assertTrue(firstUnmanagedDataDisk.vhdUri().equalsIgnoreCase(createdVhdUri1));
virtualMachine
.update()
.withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd")
.apply();
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
unmanagedDataDisks = virtualMachine.unmanagedDataDisks();
Assertions.assertNotNull(unmanagedDataDisks);
Assertions.assertEquals(2, unmanagedDataDisks.size());
}
@Test
public void canUpdateTagsOnVM() {
VirtualMachine virtualMachine =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("firstuser")
.withSsh(sshPublicKey())
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.create();
virtualMachine.update().withTag("test", "testValue").apply();
Assertions.assertEquals("testValue", virtualMachine.innerModel().tags().get("test"));
Map<String, String> testTags = new HashMap<String, String>();
testTags.put("testTag", "testValue");
virtualMachine.update().withTags(testTags).apply();
Assertions.assertEquals(testTags.get("testTag"), virtualMachine.innerModel().tags().get("testTag"));
}
@Test
public void canRunScriptOnVM() {
VirtualMachine virtualMachine =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("firstuser")
.withSsh(sshPublicKey())
.create();
List<String> installGit = new ArrayList<>();
installGit.add("sudo apt-get update");
installGit.add("sudo apt-get install -y git");
RunCommandResult runResult =
virtualMachine.runShellScript(installGit, new ArrayList<RunCommandInputParameter>());
Assertions.assertNotNull(runResult);
Assertions.assertNotNull(runResult.value());
Assertions.assertTrue(runResult.value().size() > 0);
}
@Test
@DoNotRecord(skipInPlayback = true)
public void canPerformSimulateEvictionOnSpotVirtualMachine() {
VirtualMachine virtualMachine = computeManager.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("firstuser")
.withSsh(sshPublicKey())
.withSpotPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE)
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.create();
Assertions.assertNotNull(virtualMachine.osDiskStorageAccountType());
Assertions.assertTrue(virtualMachine.osDiskSize() > 0);
Disk disk = computeManager.disks().getById(virtualMachine.osDiskId());
Assertions.assertNotNull(disk);
Assertions.assertEquals(DiskState.ATTACHED, disk.innerModel().diskState());
virtualMachine.simulateEviction();
boolean deallocated = false;
int pollIntervalInMinutes = 5;
for (int i = 0; i < 30; i += pollIntervalInMinutes) {
ResourceManagerUtils.sleep(Duration.ofMinutes(pollIntervalInMinutes));
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
if (virtualMachine.powerState() == PowerState.DEALLOCATED) {
deallocated = true;
break;
}
}
Assertions.assertTrue(deallocated);
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
Assertions.assertNotNull(virtualMachine);
Assertions.assertNull(virtualMachine.osDiskStorageAccountType());
Assertions.assertEquals(0, virtualMachine.osDiskSize());
disk = computeManager.disks().getById(virtualMachine.osDiskId());
Assertions.assertEquals(DiskState.RESERVED, disk.innerModel().diskState());
}
@Test
public void canForceDeleteVirtualMachine() {
computeManager.virtualMachines()
.define(vmName)
.withRegion("eastus2euap")
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.create();
VirtualMachine virtualMachine = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(virtualMachine);
Assertions.assertEquals(Region.fromName("eastus2euap"), virtualMachine.region());
String nicId = virtualMachine.primaryNetworkInterfaceId();
computeManager.virtualMachines().deleteById(virtualMachine.id(), true);
try {
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
} catch (ManagementException ex) {
virtualMachine = null;
Assertions.assertEquals(404, ex.getResponse().getStatusCode());
}
Assertions.assertNull(virtualMachine);
NetworkInterface nic = networkManager.networkInterfaces().getById(nicId);
Assertions.assertNotNull(nic);
}
@Test
public void canCreateVirtualMachineWithDeleteOption() throws Exception {
Region region = Region.US_WEST2;
final String publicIpDnsLabel = generateRandomResourceName("pip", 20);
Network network = this
.networkManager
.networks()
.define("network1")
.withRegion(region)
.withNewResourceGroup(rgName)
.withAddressSpace("10.0.0.0/24")
.withSubnet("default", "10.0.0.0/24")
.create();
VirtualMachine vm1 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withNewPrimaryPublicIPAddress(publicIpDnsLabel/*, DeleteOptions.DELETE*/)
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withNewDataDisk(10)
.withNewDataDisk(computeManager.disks()
.define("datadisk2")
.withRegion(region)
.withExistingResourceGroup(rgName)
.withData()
.withSizeInGB(10))
.withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE)
.withOSDiskDeleteOptions(DeleteOptions.DELETE)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
Assertions.assertEquals(DeleteOptions.DELETE, vm1.osDiskDeleteOptions());
Assertions.assertEquals(DeleteOptions.DELETE, vm1.dataDisks().get(0).deleteOptions());
Assertions.assertEquals(DeleteOptions.DELETE, vm1.dataDisks().get(1).deleteOptions());
Assertions.assertEquals(vm1.id(), computeManager.virtualMachines().getById(vm1.id()).id());
computeManager.virtualMachines().deleteById(vm1.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(2, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count());
PublicIpAddress publicIpAddress = computeManager.networkManager().publicIpAddresses().listByResourceGroup(rgName).stream().findFirst().get();
computeManager.networkManager().publicIpAddresses().deleteById(publicIpAddress.id());
String secondaryNicName = generateRandomResourceName("nic", 10);
Creatable<NetworkInterface> secondaryNetworkInterfaceCreatable =
this
.networkManager
.networkInterfaces()
.define(secondaryNicName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic();
VirtualMachine vm2 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withOSDiskDeleteOptions(DeleteOptions.DELETE)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable, DeleteOptions.DELETE)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
computeManager.virtualMachines().deleteById(vm2.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(1, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count());
secondaryNetworkInterfaceCreatable =
this
.networkManager
.networkInterfaces()
.define(secondaryNicName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic();
VirtualMachine vm3 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withNewDataDisk(10)
.withNewDataDisk(computeManager.disks()
.define("datadisk2")
.withRegion(region)
.withExistingResourceGroup(rgName)
.withData()
.withSizeInGB(10))
.withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
Assertions.assertEquals(DeleteOptions.DETACH, vm3.osDiskDeleteOptions());
Assertions.assertEquals(DeleteOptions.DETACH, vm3.dataDisks().get(0).deleteOptions());
Assertions.assertEquals(DeleteOptions.DETACH, vm3.dataDisks().get(1).deleteOptions());
computeManager.virtualMachines().deleteById(vm3.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(3, computeManager.disks().listByResourceGroup(rgName).stream().count());
Assertions.assertEquals(2, computeManager.networkManager().networkInterfaces().listByResourceGroup(rgName).stream().count());
}
@Test
public void canUpdateVirtualMachineWithDeleteOption() throws Exception {
Region region = Region.US_WEST2;
Network network = this
.networkManager
.networks()
.define("network1")
.withRegion(region)
.withNewResourceGroup(rgName)
.withAddressSpace("10.0.0.0/24")
.withSubnet("default", "10.0.0.0/24")
.create();
VirtualMachine vm1 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withNewDataDisk(10)
.withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE)
.withOSDiskDeleteOptions(DeleteOptions.DELETE)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
vm1.update()
.withNewDataDisk(10)
.apply();
computeManager.virtualMachines().deleteById(vm1.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(1, computeManager.disks().listByResourceGroup(rgName).stream().count());
Disk disk = computeManager.disks().listByResourceGroup(rgName).stream().findFirst().get();
computeManager.disks().deleteById(disk.id());
VirtualMachine vm2 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withNewDataDisk(10)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
vm2.update()
.withNewDataDisk(10)
.withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE)
.apply();
computeManager.virtualMachines().deleteById(vm2.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(2, computeManager.disks().listByResourceGroup(rgName).stream().count());
}
@Test
public void canHibernateVirtualMachine() {
VirtualMachine vm = computeManager.virtualMachines()
.define(vmName)
.withRegion("eastus2euap")
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withSize(VirtualMachineSizeTypes.STANDARD_D2S_V3)
.enableHibernation()
.create();
Assertions.assertTrue(vm.isHibernationEnabled());
vm.deallocate(true);
InstanceViewStatus hibernationStatus = vm.instanceView().statuses().stream()
.filter(status -> "HibernationState/Hibernated".equals(status.code()))
.findFirst().orElse(null);
Assertions.assertNotNull(hibernationStatus);
vm.start();
vm.deallocate();
vm.update()
.disableHibernation()
.apply();
Assertions.assertFalse(vm.isHibernationEnabled());
}
@Test
public void canOperateVirtualMachine() {
VirtualMachine vm = computeManager.virtualMachines()
.define(vmName)
.withRegion(Region.US_WEST3)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
Assertions.assertEquals(PowerState.RUNNING, vm.powerState());
vm.redeploy();
vm.powerOff(true);
vm.refreshInstanceView();
Assertions.assertEquals(PowerState.STOPPED, vm.powerState());
vm.start();
vm.refreshInstanceView();
Assertions.assertEquals(PowerState.RUNNING, vm.powerState());
vm.restart();
vm.refreshInstanceView();
Assertions.assertEquals(PowerState.RUNNING, vm.powerState());
vm.deallocate();
vm.refreshInstanceView();
Assertions.assertEquals(PowerState.DEALLOCATED, vm.powerState());
}
@Test
private CreatablesInfo prepareCreatableVirtualMachines(
Region region, String vmNamePrefix, String networkNamePrefix, String publicIpNamePrefix, int vmCount) {
Creatable<ResourceGroup> resourceGroupCreatable =
resourceManager.resourceGroups().define(rgName).withRegion(region);
Creatable<StorageAccount> storageAccountCreatable =
storageManager
.storageAccounts()
.define(generateRandomResourceName("stg", 20))
.withRegion(region)
.withNewResourceGroup(resourceGroupCreatable);
List<String> networkCreatableKeys = new ArrayList<>();
List<String> publicIpCreatableKeys = new ArrayList<>();
List<Creatable<VirtualMachine>> virtualMachineCreatables = new ArrayList<>();
for (int i = 0; i < vmCount; i++) {
Creatable<Network> networkCreatable =
networkManager
.networks()
.define(String.format("%s-%d", networkNamePrefix, i))
.withRegion(region)
.withNewResourceGroup(resourceGroupCreatable)
.withAddressSpace("10.0.0.0/28");
networkCreatableKeys.add(networkCreatable.key());
Creatable<PublicIpAddress> publicIPAddressCreatable =
networkManager
.publicIpAddresses()
.define(String.format("%s-%d", publicIpNamePrefix, i))
.withRegion(region)
.withNewResourceGroup(resourceGroupCreatable);
publicIpCreatableKeys.add(publicIPAddressCreatable.key());
Creatable<VirtualMachine> virtualMachineCreatable =
computeManager
.virtualMachines()
.define(String.format("%s-%d", vmNamePrefix, i))
.withRegion(region)
.withNewResourceGroup(resourceGroupCreatable)
.withNewPrimaryNetwork(networkCreatable)
.withPrimaryPrivateIPAddressDynamic()
.withNewPrimaryPublicIPAddress(publicIPAddressCreatable)
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("tirekicker")
.withSsh(sshPublicKey())
.withUnmanagedDisks()
.withNewStorageAccount(storageAccountCreatable);
virtualMachineCreatables.add(virtualMachineCreatable);
}
CreatablesInfo creatablesInfo = new CreatablesInfo();
creatablesInfo.virtualMachineCreatables = virtualMachineCreatables;
creatablesInfo.networkCreatableKeys = networkCreatableKeys;
creatablesInfo.publicIpCreatableKeys = publicIpCreatableKeys;
return creatablesInfo;
}
class CreatablesInfo {
private List<Creatable<VirtualMachine>> virtualMachineCreatables;
List<String> networkCreatableKeys;
List<String> publicIpCreatableKeys;
}
} | class VirtualMachineOperationsTests extends ComputeManagementTest {
private String rgName = "";
private String rgName2 = "";
private final Region region = Region.US_EAST;
private final Region regionProxPlacementGroup = Region.US_WEST;
private final Region regionProxPlacementGroup2 = Region.US_EAST;
private final String vmName = "javavm";
private final String proxGroupName = "testproxgroup1";
private final String proxGroupName2 = "testproxgroup2";
private final String availabilitySetName = "availset1";
private final String availabilitySetName2 = "availset2";
private final ProximityPlacementGroupType proxGroupType = ProximityPlacementGroupType.STANDARD;
@Override
protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) {
rgName = generateRandomResourceName("javacsmrg", 15);
rgName2 = generateRandomResourceName("javacsmrg2", 15);
super.initializeClients(httpPipeline, profile);
}
@Override
protected void cleanUpResources() {
if (rgName != null) {
resourceManager.resourceGroups().beginDeleteByName(rgName);
}
}
@Test
public void canCreateVirtualMachineWithNetworking() throws Exception {
NetworkSecurityGroup nsg =
this
.networkManager
.networkSecurityGroups()
.define("nsg")
.withRegion(region)
.withNewResourceGroup(rgName)
.defineRule("rule1")
.allowInbound()
.fromAnyAddress()
.fromPort(80)
.toAnyAddress()
.toPort(80)
.withProtocol(SecurityRuleProtocol.TCP)
.attach()
.create();
Creatable<Network> networkDefinition =
this
.networkManager
.networks()
.define("network1")
.withRegion(region)
.withNewResourceGroup(rgName)
.withAddressSpace("10.0.0.0/28")
.defineSubnet("subnet1")
.withAddressPrefix("10.0.0.0/29")
.withExistingNetworkSecurityGroup(nsg)
.attach();
VirtualMachine vm =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork(networkDefinition)
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.create();
NetworkInterface primaryNic = vm.getPrimaryNetworkInterface();
Assertions.assertNotNull(primaryNic);
NicIpConfiguration primaryIpConfig = primaryNic.primaryIPConfiguration();
Assertions.assertNotNull(primaryIpConfig);
Assertions.assertNotNull(primaryIpConfig.networkId());
Network network = primaryIpConfig.getNetwork();
Assertions.assertNotNull(primaryIpConfig.subnetName());
Subnet subnet = network.subnets().get(primaryIpConfig.subnetName());
Assertions.assertNotNull(subnet);
nsg = subnet.getNetworkSecurityGroup();
Assertions.assertNotNull(nsg);
Assertions.assertEquals("nsg", nsg.name());
Assertions.assertEquals(1, nsg.securityRules().size());
nsg = primaryIpConfig.getNetworkSecurityGroup();
Assertions.assertEquals("nsg", nsg.name());
}
@Test
public void canCreateVirtualMachine() throws Exception {
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLicenseType("Windows_Server")
.create();
VirtualMachine foundVM = null;
PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName);
for (VirtualMachine vm1 : vms) {
if (vm1.name().equals(vmName)) {
foundVM = vm1;
break;
}
}
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(region, foundVM.region());
foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(region, foundVM.region());
Assertions.assertEquals("Windows_Server", foundVM.licenseType());
PowerState powerState = foundVM.powerState();
Assertions.assertEquals(powerState, PowerState.RUNNING);
VirtualMachineInstanceView instanceView = foundVM.instanceView();
Assertions.assertNotNull(instanceView);
Assertions.assertNotNull(instanceView.statuses().size() > 0);
computeManager.virtualMachines().deleteById(foundVM.id());
}
@Test
public void cannotCreateVirtualMachineSyncPoll() throws Exception {
final String mySqlInstallScript = "https:
final String installCommand = "bash install_mysql_server_5.6.sh Abc.123x(";
Assertions.assertThrows(IllegalStateException.class, () -> {
Accepted<VirtualMachine> acceptedVirtualMachine =
this.computeManager.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.defineNewExtension("CustomScriptForLinux")
.withPublisher("Microsoft.OSTCExtensions")
.withType("CustomScriptForLinux")
.withVersion("1.4")
.withMinorVersionAutoUpgrade()
.withPublicSetting("fileUris", Collections.singletonList(mySqlInstallScript))
.withPublicSetting("commandToExecute", installCommand)
.attach()
.beginCreate();
});
boolean dependentResourceCreated = computeManager.resourceManager().serviceClient().getResourceGroups().checkExistence(rgName);
Assertions.assertFalse(dependentResourceCreated);
rgName = null;
}
@Test
public void canCreateVirtualMachineSyncPoll() throws Exception {
final long defaultDelayInMillis = 10 * 1000;
Accepted<VirtualMachine> acceptedVirtualMachine = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLicenseType("Windows_Server")
.beginCreate();
VirtualMachine createdVirtualMachine = acceptedVirtualMachine.getActivationResponse().getValue();
Assertions.assertNotEquals("Succeeded", createdVirtualMachine.provisioningState());
LongRunningOperationStatus pollStatus = acceptedVirtualMachine.getActivationResponse().getStatus();
long delayInMills = acceptedVirtualMachine.getActivationResponse().getRetryAfter() == null
? defaultDelayInMillis
: acceptedVirtualMachine.getActivationResponse().getRetryAfter().toMillis();
while (!pollStatus.isComplete()) {
ResourceManagerUtils.sleep(Duration.ofMillis(delayInMills));
PollResponse<?> pollResponse = acceptedVirtualMachine.getSyncPoller().poll();
pollStatus = pollResponse.getStatus();
delayInMills = pollResponse.getRetryAfter() == null
? defaultDelayInMillis
: pollResponse.getRetryAfter().toMillis();
}
Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollStatus);
VirtualMachine virtualMachine = acceptedVirtualMachine.getFinalResult();
Assertions.assertEquals("Succeeded", virtualMachine.provisioningState());
Accepted<Void> acceptedDelete = computeManager.virtualMachines()
.beginDeleteByResourceGroup(virtualMachine.resourceGroupName(), virtualMachine.name());
pollStatus = acceptedDelete.getActivationResponse().getStatus();
delayInMills = acceptedDelete.getActivationResponse().getRetryAfter() == null
? defaultDelayInMillis
: (int) acceptedDelete.getActivationResponse().getRetryAfter().toMillis();
while (!pollStatus.isComplete()) {
ResourceManagerUtils.sleep(Duration.ofMillis(delayInMills));
PollResponse<?> pollResponse = acceptedDelete.getSyncPoller().poll();
pollStatus = pollResponse.getStatus();
delayInMills = pollResponse.getRetryAfter() == null
? defaultDelayInMillis
: (int) pollResponse.getRetryAfter().toMillis();
}
boolean deleted = false;
try {
computeManager.virtualMachines().getById(virtualMachine.id());
} catch (ManagementException e) {
if (e.getResponse().getStatusCode() == 404
&& ("NotFound".equals(e.getValue().getCode()) || "ResourceNotFound".equals(e.getValue().getCode()))) {
deleted = true;
}
}
Assertions.assertTrue(deleted);
}
@Test
public void canCreateUpdatePriorityAndPrice() throws Exception {
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLowPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE)
.withMaxPrice(1000.0)
.withLicenseType("Windows_Server")
.create();
VirtualMachine foundVM = null;
PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName);
for (VirtualMachine vm1 : vms) {
if (vm1.name().equals(vmName)) {
foundVM = vm1;
break;
}
}
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(region, foundVM.region());
foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(region, foundVM.region());
Assertions.assertEquals("Windows_Server", foundVM.licenseType());
Assertions.assertEquals((Double) 1000.0, foundVM.billingProfile().maxPrice());
Assertions.assertEquals(VirtualMachineEvictionPolicyTypes.DEALLOCATE, foundVM.evictionPolicy());
try {
foundVM.update().withMaxPrice(1500.0).apply();
Assertions.assertEquals((Double) 1500.0, foundVM.billingProfile().maxPrice());
Assertions.fail();
} catch (ManagementException e) {
}
foundVM.deallocate();
foundVM.update().withMaxPrice(2000.0).apply();
foundVM.start();
Assertions.assertEquals((Double) 2000.0, foundVM.billingProfile().maxPrice());
foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.SPOT).apply();
Assertions.assertEquals(VirtualMachinePriorityTypes.SPOT, foundVM.priority());
foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.LOW).apply();
Assertions.assertEquals(VirtualMachinePriorityTypes.LOW, foundVM.priority());
try {
foundVM.update().withPriority(VirtualMachinePriorityTypes.REGULAR).apply();
Assertions.assertEquals(VirtualMachinePriorityTypes.REGULAR, foundVM.priority());
Assertions.fail();
} catch (ManagementException e) {
}
computeManager.virtualMachines().deleteById(foundVM.id());
}
@Test
public void cannotUpdateProximityPlacementGroupForVirtualMachine() throws Exception {
AvailabilitySet setCreated =
computeManager
.availabilitySets()
.define(availabilitySetName)
.withRegion(regionProxPlacementGroup)
.withNewResourceGroup(rgName)
.withNewProximityPlacementGroup(proxGroupName, proxGroupType)
.create();
Assertions.assertEquals(availabilitySetName, setCreated.name());
Assertions.assertNotNull(setCreated.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location());
AvailabilitySet setCreated2 =
computeManager
.availabilitySets()
.define(availabilitySetName2)
.withRegion(regionProxPlacementGroup2)
.withNewResourceGroup(rgName2)
.withNewProximityPlacementGroup(proxGroupName2, proxGroupType)
.create();
Assertions.assertEquals(availabilitySetName2, setCreated2.name());
Assertions.assertNotNull(setCreated2.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, setCreated2.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(setCreated2.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(setCreated2.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated2.id().equalsIgnoreCase(setCreated2.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertEquals(setCreated2.regionName(), setCreated2.proximityPlacementGroup().location());
computeManager
.virtualMachines()
.define(vmName)
.withRegion(regionProxPlacementGroup)
.withExistingResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withProximityPlacementGroup(setCreated.proximityPlacementGroup().id())
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLicenseType("Windows_Server")
.create();
VirtualMachine foundVM = null;
PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName);
for (VirtualMachine vm1 : vms) {
if (vm1.name().equals(vmName)) {
foundVM = vm1;
break;
}
}
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(regionProxPlacementGroup, foundVM.region());
foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(regionProxPlacementGroup, foundVM.region());
Assertions.assertEquals("Windows_Server", foundVM.licenseType());
PowerState powerState = foundVM.powerState();
Assertions.assertEquals(powerState, PowerState.RUNNING);
VirtualMachineInstanceView instanceView = foundVM.instanceView();
Assertions.assertNotNull(instanceView);
Assertions.assertNotNull(instanceView.statuses().size() > 0);
Assertions.assertNotNull(foundVM.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds());
Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty());
Assertions
.assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0)));
try {
VirtualMachine updatedVm =
foundVM.update().withProximityPlacementGroup(setCreated2.proximityPlacementGroup().id()).apply();
} catch (ManagementException clEx) {
Assertions
.assertTrue(
clEx
.getMessage()
.contains(
"Updating proximity placement group of VM javavm is not allowed while the VM is running."
+ " Please stop/deallocate the VM and retry the operation."));
}
computeManager.virtualMachines().deleteById(foundVM.id());
computeManager.availabilitySets().deleteById(setCreated.id());
}
@Test
public void canCreateVirtualMachinesAndAvailabilitySetInSameProximityPlacementGroup() throws Exception {
AvailabilitySet setCreated =
computeManager
.availabilitySets()
.define(availabilitySetName)
.withRegion(regionProxPlacementGroup)
.withNewResourceGroup(rgName)
.withNewProximityPlacementGroup(proxGroupName, proxGroupType)
.create();
Assertions.assertEquals(availabilitySetName, setCreated.name());
Assertions.assertNotNull(setCreated.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location());
computeManager
.virtualMachines()
.define(vmName)
.withRegion(regionProxPlacementGroup)
.withExistingResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withProximityPlacementGroup(setCreated.proximityPlacementGroup().id())
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLicenseType("Windows_Server")
.create();
VirtualMachine foundVM = null;
PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName);
for (VirtualMachine vm1 : vms) {
if (vm1.name().equals(vmName)) {
foundVM = vm1;
break;
}
}
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(regionProxPlacementGroup, foundVM.region());
foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(regionProxPlacementGroup, foundVM.region());
Assertions.assertEquals("Windows_Server", foundVM.licenseType());
PowerState powerState = foundVM.powerState();
Assertions.assertEquals(powerState, PowerState.RUNNING);
VirtualMachineInstanceView instanceView = foundVM.instanceView();
Assertions.assertNotNull(instanceView);
Assertions.assertNotNull(instanceView.statuses().size() > 0);
Assertions.assertNotNull(foundVM.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds());
Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty());
Assertions
.assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0)));
VirtualMachine updatedVm = foundVM.update().withoutProximityPlacementGroup().apply();
Assertions.assertNotNull(updatedVm.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, updatedVm.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(updatedVm.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(updatedVm.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(updatedVm.proximityPlacementGroup().availabilitySetIds().get(0)));
computeManager.virtualMachines().deleteById(foundVM.id());
computeManager.availabilitySets().deleteById(setCreated.id());
}
@Test
public void canCreateVirtualMachinesAndRelatedResourcesInParallel() throws Exception {
String vmNamePrefix = "vmz";
String publicIpNamePrefix = generateRandomResourceName("pip-", 15);
String networkNamePrefix = generateRandomResourceName("vnet-", 15);
int count = 5;
CreatablesInfo creatablesInfo =
prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count);
List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables;
List<String> networkCreatableKeys = creatablesInfo.networkCreatableKeys;
List<String> publicIpCreatableKeys = creatablesInfo.publicIpCreatableKeys;
CreatedResources<VirtualMachine> createdVirtualMachines =
computeManager.virtualMachines().create(virtualMachineCreatables);
Assertions.assertTrue(createdVirtualMachines.size() == count);
Set<String> virtualMachineNames = new HashSet<>();
for (int i = 0; i < count; i++) {
virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i));
}
for (VirtualMachine virtualMachine : createdVirtualMachines.values()) {
Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name()));
Assertions.assertNotNull(virtualMachine.id());
}
Set<String> networkNames = new HashSet<>();
for (int i = 0; i < count; i++) {
networkNames.add(String.format("%s-%d", networkNamePrefix, i));
}
for (String networkCreatableKey : networkCreatableKeys) {
Network createdNetwork = (Network) createdVirtualMachines.createdRelatedResource(networkCreatableKey);
Assertions.assertNotNull(createdNetwork);
Assertions.assertTrue(networkNames.contains(createdNetwork.name()));
}
Set<String> publicIPAddressNames = new HashSet<>();
for (int i = 0; i < count; i++) {
publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i));
}
for (String publicIpCreatableKey : publicIpCreatableKeys) {
PublicIpAddress createdPublicIpAddress =
(PublicIpAddress) createdVirtualMachines.createdRelatedResource(publicIpCreatableKey);
Assertions.assertNotNull(createdPublicIpAddress);
Assertions.assertTrue(publicIPAddressNames.contains(createdPublicIpAddress.name()));
}
}
@Test
public void canStreamParallelCreatedVirtualMachinesAndRelatedResources() throws Exception {
String vmNamePrefix = "vmz";
String publicIpNamePrefix = generateRandomResourceName("pip-", 15);
String networkNamePrefix = generateRandomResourceName("vnet-", 15);
int count = 5;
final Set<String> virtualMachineNames = new HashSet<>();
for (int i = 0; i < count; i++) {
virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i));
}
final Set<String> networkNames = new HashSet<>();
for (int i = 0; i < count; i++) {
networkNames.add(String.format("%s-%d", networkNamePrefix, i));
}
final Set<String> publicIPAddressNames = new HashSet<>();
for (int i = 0; i < count; i++) {
publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i));
}
final CreatablesInfo creatablesInfo =
prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count);
final AtomicInteger resourceCount = new AtomicInteger(0);
List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables;
computeManager
.virtualMachines()
.createAsync(virtualMachineCreatables)
.map(
createdResource -> {
if (createdResource instanceof Resource) {
Resource resource = (Resource) createdResource;
System.out.println("Created: " + resource.id());
if (resource instanceof VirtualMachine) {
VirtualMachine virtualMachine = (VirtualMachine) resource;
Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name()));
Assertions.assertNotNull(virtualMachine.id());
} else if (resource instanceof Network) {
Network network = (Network) resource;
Assertions.assertTrue(networkNames.contains(network.name()));
Assertions.assertNotNull(network.id());
} else if (resource instanceof PublicIpAddress) {
PublicIpAddress publicIPAddress = (PublicIpAddress) resource;
Assertions.assertTrue(publicIPAddressNames.contains(publicIPAddress.name()));
Assertions.assertNotNull(publicIPAddress.id());
}
}
resourceCount.incrementAndGet();
return createdResource;
})
.blockLast();
networkNames.forEach(name -> {
Assertions.assertNotNull(networkManager.networks().getByResourceGroup(rgName, name));
});
publicIPAddressNames.forEach(name -> {
Assertions.assertNotNull(networkManager.publicIpAddresses().getByResourceGroup(rgName, name));
});
Assertions.assertEquals(1, storageManager.storageAccounts().listByResourceGroup(rgName).stream().count());
Assertions.assertEquals(count, networkManager.networkInterfaces().listByResourceGroup(rgName).stream().count());
Assertions.assertEquals(count, resourceCount.get());
}
@Test
public void canSetStorageAccountForUnmanagedDisk() {
final String storageName = generateRandomResourceName("st", 14);
StorageAccount storageAccount =
storageManager
.storageAccounts()
.define(storageName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withSku(StorageAccountSkuType.PREMIUM_LRS)
.create();
VirtualMachine virtualMachine =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.withUnmanagedDisks()
.defineUnmanagedDataDisk("disk1")
.withNewVhd(100)
.withLun(2)
.storeAt(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd")
.attach()
.defineUnmanagedDataDisk("disk2")
.withNewVhd(100)
.withLun(3)
.storeAt(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd")
.attach()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.create();
Map<Integer, VirtualMachineUnmanagedDataDisk> unmanagedDataDisks = virtualMachine.unmanagedDataDisks();
Assertions.assertNotNull(unmanagedDataDisks);
Assertions.assertEquals(2, unmanagedDataDisks.size());
VirtualMachineUnmanagedDataDisk firstUnmanagedDataDisk = unmanagedDataDisks.get(2);
Assertions.assertNotNull(firstUnmanagedDataDisk);
VirtualMachineUnmanagedDataDisk secondUnmanagedDataDisk = unmanagedDataDisks.get(3);
Assertions.assertNotNull(secondUnmanagedDataDisk);
String createdVhdUri1 = firstUnmanagedDataDisk.vhdUri();
String createdVhdUri2 = secondUnmanagedDataDisk.vhdUri();
Assertions.assertNotNull(createdVhdUri1);
Assertions.assertNotNull(createdVhdUri2);
computeManager.virtualMachines().deleteById(virtualMachine.id());
virtualMachine =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.withUnmanagedDisks()
.withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd")
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4"))
.create();
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
unmanagedDataDisks = virtualMachine.unmanagedDataDisks();
Assertions.assertNotNull(unmanagedDataDisks);
Assertions.assertEquals(1, unmanagedDataDisks.size());
firstUnmanagedDataDisk = null;
for (VirtualMachineUnmanagedDataDisk unmanagedDisk : unmanagedDataDisks.values()) {
firstUnmanagedDataDisk = unmanagedDisk;
break;
}
Assertions.assertNotNull(firstUnmanagedDataDisk.vhdUri());
Assertions.assertTrue(firstUnmanagedDataDisk.vhdUri().equalsIgnoreCase(createdVhdUri1));
virtualMachine
.update()
.withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd")
.apply();
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
unmanagedDataDisks = virtualMachine.unmanagedDataDisks();
Assertions.assertNotNull(unmanagedDataDisks);
Assertions.assertEquals(2, unmanagedDataDisks.size());
}
@Test
public void canUpdateTagsOnVM() {
VirtualMachine virtualMachine =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("firstuser")
.withSsh(sshPublicKey())
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.create();
virtualMachine.update().withTag("test", "testValue").apply();
Assertions.assertEquals("testValue", virtualMachine.innerModel().tags().get("test"));
Map<String, String> testTags = new HashMap<String, String>();
testTags.put("testTag", "testValue");
virtualMachine.update().withTags(testTags).apply();
Assertions.assertEquals(testTags.get("testTag"), virtualMachine.innerModel().tags().get("testTag"));
}
@Test
public void canRunScriptOnVM() {
VirtualMachine virtualMachine =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("firstuser")
.withSsh(sshPublicKey())
.create();
List<String> installGit = new ArrayList<>();
installGit.add("sudo apt-get update");
installGit.add("sudo apt-get install -y git");
RunCommandResult runResult =
virtualMachine.runShellScript(installGit, new ArrayList<RunCommandInputParameter>());
Assertions.assertNotNull(runResult);
Assertions.assertNotNull(runResult.value());
Assertions.assertTrue(runResult.value().size() > 0);
}
@Test
@DoNotRecord(skipInPlayback = true)
public void canPerformSimulateEvictionOnSpotVirtualMachine() {
VirtualMachine virtualMachine = computeManager.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("firstuser")
.withSsh(sshPublicKey())
.withSpotPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE)
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.create();
Assertions.assertNotNull(virtualMachine.osDiskStorageAccountType());
Assertions.assertTrue(virtualMachine.osDiskSize() > 0);
Disk disk = computeManager.disks().getById(virtualMachine.osDiskId());
Assertions.assertNotNull(disk);
Assertions.assertEquals(DiskState.ATTACHED, disk.innerModel().diskState());
virtualMachine.simulateEviction();
boolean deallocated = false;
int pollIntervalInMinutes = 5;
for (int i = 0; i < 30; i += pollIntervalInMinutes) {
ResourceManagerUtils.sleep(Duration.ofMinutes(pollIntervalInMinutes));
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
if (virtualMachine.powerState() == PowerState.DEALLOCATED) {
deallocated = true;
break;
}
}
Assertions.assertTrue(deallocated);
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
Assertions.assertNotNull(virtualMachine);
Assertions.assertNull(virtualMachine.osDiskStorageAccountType());
Assertions.assertEquals(0, virtualMachine.osDiskSize());
disk = computeManager.disks().getById(virtualMachine.osDiskId());
Assertions.assertEquals(DiskState.RESERVED, disk.innerModel().diskState());
}
@Test
public void canForceDeleteVirtualMachine() {
computeManager.virtualMachines()
.define(vmName)
.withRegion("eastus2euap")
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.create();
VirtualMachine virtualMachine = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(virtualMachine);
Assertions.assertEquals(Region.fromName("eastus2euap"), virtualMachine.region());
String nicId = virtualMachine.primaryNetworkInterfaceId();
computeManager.virtualMachines().deleteById(virtualMachine.id(), true);
try {
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
} catch (ManagementException ex) {
virtualMachine = null;
Assertions.assertEquals(404, ex.getResponse().getStatusCode());
}
Assertions.assertNull(virtualMachine);
NetworkInterface nic = networkManager.networkInterfaces().getById(nicId);
Assertions.assertNotNull(nic);
}
@Test
public void canCreateVirtualMachineWithDeleteOption() throws Exception {
Region region = Region.US_WEST2;
final String publicIpDnsLabel = generateRandomResourceName("pip", 20);
Network network = this
.networkManager
.networks()
.define("network1")
.withRegion(region)
.withNewResourceGroup(rgName)
.withAddressSpace("10.0.0.0/24")
.withSubnet("default", "10.0.0.0/24")
.create();
VirtualMachine vm1 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withNewPrimaryPublicIPAddress(publicIpDnsLabel/*, DeleteOptions.DELETE*/)
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withNewDataDisk(10)
.withNewDataDisk(computeManager.disks()
.define("datadisk2")
.withRegion(region)
.withExistingResourceGroup(rgName)
.withData()
.withSizeInGB(10))
.withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE)
.withOSDiskDeleteOptions(DeleteOptions.DELETE)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
Assertions.assertEquals(DeleteOptions.DELETE, vm1.osDiskDeleteOptions());
Assertions.assertEquals(DeleteOptions.DELETE, vm1.dataDisks().get(0).deleteOptions());
Assertions.assertEquals(DeleteOptions.DELETE, vm1.dataDisks().get(1).deleteOptions());
Assertions.assertEquals(vm1.id(), computeManager.virtualMachines().getById(vm1.id()).id());
computeManager.virtualMachines().deleteById(vm1.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(2, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count());
PublicIpAddress publicIpAddress = computeManager.networkManager().publicIpAddresses().listByResourceGroup(rgName).stream().findFirst().get();
computeManager.networkManager().publicIpAddresses().deleteById(publicIpAddress.id());
String secondaryNicName = generateRandomResourceName("nic", 10);
Creatable<NetworkInterface> secondaryNetworkInterfaceCreatable =
this
.networkManager
.networkInterfaces()
.define(secondaryNicName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic();
VirtualMachine vm2 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withOSDiskDeleteOptions(DeleteOptions.DELETE)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable, DeleteOptions.DELETE)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
computeManager.virtualMachines().deleteById(vm2.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(1, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count());
secondaryNetworkInterfaceCreatable =
this
.networkManager
.networkInterfaces()
.define(secondaryNicName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic();
VirtualMachine vm3 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withNewDataDisk(10)
.withNewDataDisk(computeManager.disks()
.define("datadisk2")
.withRegion(region)
.withExistingResourceGroup(rgName)
.withData()
.withSizeInGB(10))
.withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
Assertions.assertEquals(DeleteOptions.DETACH, vm3.osDiskDeleteOptions());
Assertions.assertEquals(DeleteOptions.DETACH, vm3.dataDisks().get(0).deleteOptions());
Assertions.assertEquals(DeleteOptions.DETACH, vm3.dataDisks().get(1).deleteOptions());
computeManager.virtualMachines().deleteById(vm3.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(3, computeManager.disks().listByResourceGroup(rgName).stream().count());
Assertions.assertEquals(2, computeManager.networkManager().networkInterfaces().listByResourceGroup(rgName).stream().count());
}
@Test
public void canUpdateVirtualMachineWithDeleteOption() throws Exception {
Region region = Region.US_WEST2;
Network network = this
.networkManager
.networks()
.define("network1")
.withRegion(region)
.withNewResourceGroup(rgName)
.withAddressSpace("10.0.0.0/24")
.withSubnet("default", "10.0.0.0/24")
.create();
VirtualMachine vm1 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withNewDataDisk(10)
.withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE)
.withOSDiskDeleteOptions(DeleteOptions.DELETE)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
vm1.update()
.withNewDataDisk(10)
.apply();
computeManager.virtualMachines().deleteById(vm1.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(1, computeManager.disks().listByResourceGroup(rgName).stream().count());
Disk disk = computeManager.disks().listByResourceGroup(rgName).stream().findFirst().get();
computeManager.disks().deleteById(disk.id());
VirtualMachine vm2 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withNewDataDisk(10)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
vm2.update()
.withNewDataDisk(10)
.withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE)
.apply();
computeManager.virtualMachines().deleteById(vm2.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(2, computeManager.disks().listByResourceGroup(rgName).stream().count());
}
@Test
public void canHibernateVirtualMachine() {
VirtualMachine vm = computeManager.virtualMachines()
.define(vmName)
.withRegion("eastus2euap")
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withSize(VirtualMachineSizeTypes.STANDARD_D2S_V3)
.enableHibernation()
.create();
Assertions.assertTrue(vm.isHibernationEnabled());
vm.deallocate(true);
InstanceViewStatus hibernationStatus = vm.instanceView().statuses().stream()
.filter(status -> "HibernationState/Hibernated".equals(status.code()))
.findFirst().orElse(null);
Assertions.assertNotNull(hibernationStatus);
vm.start();
vm.deallocate();
vm.update()
.disableHibernation()
.apply();
Assertions.assertFalse(vm.isHibernationEnabled());
}
@Test
public void canOperateVirtualMachine() {
VirtualMachine vm = computeManager.virtualMachines()
.define(vmName)
.withRegion(Region.US_WEST3)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
Assertions.assertEquals(PowerState.RUNNING, vm.powerState());
vm.redeploy();
vm.powerOff(true);
vm.refreshInstanceView();
Assertions.assertEquals(PowerState.STOPPED, vm.powerState());
vm.start();
vm.refreshInstanceView();
Assertions.assertEquals(PowerState.RUNNING, vm.powerState());
vm.restart();
vm.refreshInstanceView();
Assertions.assertEquals(PowerState.RUNNING, vm.powerState());
vm.deallocate();
vm.refreshInstanceView();
Assertions.assertEquals(PowerState.DEALLOCATED, vm.powerState());
}
@Test
private CreatablesInfo prepareCreatableVirtualMachines(
Region region, String vmNamePrefix, String networkNamePrefix, String publicIpNamePrefix, int vmCount) {
Creatable<ResourceGroup> resourceGroupCreatable =
resourceManager.resourceGroups().define(rgName).withRegion(region);
Creatable<StorageAccount> storageAccountCreatable =
storageManager
.storageAccounts()
.define(generateRandomResourceName("stg", 20))
.withRegion(region)
.withNewResourceGroup(resourceGroupCreatable);
List<String> networkCreatableKeys = new ArrayList<>();
List<String> publicIpCreatableKeys = new ArrayList<>();
List<Creatable<VirtualMachine>> virtualMachineCreatables = new ArrayList<>();
for (int i = 0; i < vmCount; i++) {
Creatable<Network> networkCreatable =
networkManager
.networks()
.define(String.format("%s-%d", networkNamePrefix, i))
.withRegion(region)
.withNewResourceGroup(resourceGroupCreatable)
.withAddressSpace("10.0.0.0/28");
networkCreatableKeys.add(networkCreatable.key());
Creatable<PublicIpAddress> publicIPAddressCreatable =
networkManager
.publicIpAddresses()
.define(String.format("%s-%d", publicIpNamePrefix, i))
.withRegion(region)
.withNewResourceGroup(resourceGroupCreatable);
publicIpCreatableKeys.add(publicIPAddressCreatable.key());
Creatable<VirtualMachine> virtualMachineCreatable =
computeManager
.virtualMachines()
.define(String.format("%s-%d", vmNamePrefix, i))
.withRegion(region)
.withNewResourceGroup(resourceGroupCreatable)
.withNewPrimaryNetwork(networkCreatable)
.withPrimaryPrivateIPAddressDynamic()
.withNewPrimaryPublicIPAddress(publicIPAddressCreatable)
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("tirekicker")
.withSsh(sshPublicKey())
.withUnmanagedDisks()
.withNewStorageAccount(storageAccountCreatable);
virtualMachineCreatables.add(virtualMachineCreatable);
}
CreatablesInfo creatablesInfo = new CreatablesInfo();
creatablesInfo.virtualMachineCreatables = virtualMachineCreatables;
creatablesInfo.networkCreatableKeys = networkCreatableKeys;
creatablesInfo.publicIpCreatableKeys = publicIpCreatableKeys;
return creatablesInfo;
}
class CreatablesInfo {
private List<Creatable<VirtualMachine>> virtualMachineCreatables;
List<String> networkCreatableKeys;
List<String> publicIpCreatableKeys;
}
} |
It is guaranteed that when `httpClient` ***is null***, TestMode is `PLAYBACK` | protected PhoneNumbersClientBuilder getClientBuilderUsingManagedIdentity(HttpClient httpClient) {
PhoneNumbersClientBuilder builder = new PhoneNumbersClientBuilder();
builder
.httpClient(getHttpClient(httpClient))
.addPolicy(getOverrideMSUseragentPolicy())
.endpoint(new CommunicationConnectionString(CONNECTION_STRING).getEndpoint());
if (getTestMode() == TestMode.PLAYBACK) {
builder.credential(new FakeCredentials());
} else {
builder.credential(new DefaultAzureCredentialBuilder().build());
}
if (shouldRecord()) {
builder.addPolicy(getRecordPolicy());
}
return builder;
} | builder.credential(new FakeCredentials()); | protected PhoneNumbersClientBuilder getClientBuilderUsingManagedIdentity(HttpClient httpClient) {
PhoneNumbersClientBuilder builder = new PhoneNumbersClientBuilder();
builder
.httpClient(getHttpClient(httpClient))
.addPolicy(getOverrideMSUserAgentPolicy())
.endpoint(new CommunicationConnectionString(CONNECTION_STRING).getEndpoint());
if (getTestMode() == TestMode.PLAYBACK) {
builder.credential(new FakeCredentials());
} else {
builder.credential(new DefaultAzureCredentialBuilder().build());
}
if (shouldRecord()) {
builder.addPolicy(getRecordPolicy());
}
return builder;
} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} | class PhoneNumbersIntegrationTestBase extends TestBase {
private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration()
.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", "endpoint=https:
protected static final String COUNTRY_CODE =
Configuration.getGlobalConfiguration().get("COUNTRY_CODE", "US");
protected static final String AREA_CODE =
Configuration.getGlobalConfiguration().get("AREA_CODE", "833");
protected static final String MS_USERAGENT_OVERRIDE = Configuration.getGlobalConfiguration().get("AZURE_USERAGENT_OVERRIDE", "");
private static final StringJoiner JSON_PROPERTIES_TO_REDACT =
new StringJoiner("\":\"|\"", "\"", "\":\"")
.add("id")
.add("phoneNumber");
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN =
Pattern.compile(String.format("(?:%s)(.*?)(?:\",|\"} |
👍 | protected void doStop() {
this.delegate.stop();
} | this.delegate.stop(); | protected void doStop() {
this.delegate.stop();
} | class ServiceBusMessageListenerContainer extends AbstractMessageListenerContainer {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceBusMessageListenerContainer.class);
private final ServiceBusProcessorFactory processorFactory;
private final ServiceBusContainerProperties containerProperties;
private ServiceBusErrorHandler errorHandler;
private ServiceBusProcessorClient delegate;
/**
* Create an instance using the supplied processor factory and container properties.
*
* @param processorFactory the processor factory.
* @param containerProperties the container properties.
*/
public ServiceBusMessageListenerContainer(ServiceBusProcessorFactory processorFactory,
ServiceBusContainerProperties containerProperties) {
this.processorFactory = processorFactory;
this.containerProperties = containerProperties == null ? new ServiceBusContainerProperties() : containerProperties;
}
@Override
protected void doStart() {
String entityName = containerProperties.getEntityName();
String subscriptionName = containerProperties.getSubscriptionName();
if (this.errorHandler != null) {
this.containerProperties.setErrorHandler(errorHandler);
}
if (StringUtils.hasText(subscriptionName)) {
this.delegate = this.processorFactory.createProcessor(entityName, subscriptionName, containerProperties);
} else {
this.delegate = this.processorFactory.createProcessor(entityName, containerProperties);
}
this.delegate.start();
}
@Override
@Override
public void setupMessageListener(Object messageListener) {
this.containerProperties.setMessageListener((ServiceBusMessageListener) messageListener);
}
@Override
public ServiceBusContainerProperties getContainerProperties() {
return containerProperties;
}
/**
* Set the error handler to call when the listener throws an exception.
* @param errorHandler the error handler.
*/
public void setErrorHandler(ServiceBusErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
} | class ServiceBusMessageListenerContainer extends AbstractMessageListenerContainer {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceBusMessageListenerContainer.class);
private final ServiceBusProcessorFactory processorFactory;
private final ServiceBusContainerProperties containerProperties;
private ServiceBusErrorHandler errorHandler;
private ServiceBusProcessorClient delegate;
/**
* Create an instance using the supplied processor factory and container properties.
*
* @param processorFactory the processor factory.
* @param containerProperties the container properties.
*/
public ServiceBusMessageListenerContainer(ServiceBusProcessorFactory processorFactory,
ServiceBusContainerProperties containerProperties) {
this.processorFactory = processorFactory;
this.containerProperties = containerProperties == null ? new ServiceBusContainerProperties() : containerProperties;
}
@Override
protected void doStart() {
String entityName = containerProperties.getEntityName();
String subscriptionName = containerProperties.getSubscriptionName();
if (this.errorHandler != null) {
this.containerProperties.setErrorHandler(errorHandler);
}
if (StringUtils.hasText(subscriptionName)) {
this.delegate = this.processorFactory.createProcessor(entityName, subscriptionName, containerProperties);
} else {
this.delegate = this.processorFactory.createProcessor(entityName, containerProperties);
}
this.delegate.start();
}
@Override
@Override
public void setupMessageListener(Object messageListener) {
this.containerProperties.setMessageListener((ServiceBusMessageListener) messageListener);
}
@Override
public ServiceBusContainerProperties getContainerProperties() {
return containerProperties;
}
/**
* Set the error handler to call when the listener throws an exception.
* @param errorHandler the error handler.
*/
public void setErrorHandler(ServiceBusErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
} |
good catch | protected void doStop() {
this.delegate.stop();
} | this.delegate.stop(); | protected void doStop() {
this.delegate.stop();
} | class ServiceBusMessageListenerContainer extends AbstractMessageListenerContainer {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceBusMessageListenerContainer.class);
private final ServiceBusProcessorFactory processorFactory;
private final ServiceBusContainerProperties containerProperties;
private ServiceBusErrorHandler errorHandler;
private ServiceBusProcessorClient delegate;
/**
* Create an instance using the supplied processor factory and container properties.
*
* @param processorFactory the processor factory.
* @param containerProperties the container properties.
*/
public ServiceBusMessageListenerContainer(ServiceBusProcessorFactory processorFactory,
ServiceBusContainerProperties containerProperties) {
this.processorFactory = processorFactory;
this.containerProperties = containerProperties == null ? new ServiceBusContainerProperties() : containerProperties;
}
@Override
protected void doStart() {
String entityName = containerProperties.getEntityName();
String subscriptionName = containerProperties.getSubscriptionName();
if (this.errorHandler != null) {
this.containerProperties.setErrorHandler(errorHandler);
}
if (StringUtils.hasText(subscriptionName)) {
this.delegate = this.processorFactory.createProcessor(entityName, subscriptionName, containerProperties);
} else {
this.delegate = this.processorFactory.createProcessor(entityName, containerProperties);
}
this.delegate.start();
}
@Override
@Override
public void setupMessageListener(Object messageListener) {
this.containerProperties.setMessageListener((ServiceBusMessageListener) messageListener);
}
@Override
public ServiceBusContainerProperties getContainerProperties() {
return containerProperties;
}
/**
* Set the error handler to call when the listener throws an exception.
* @param errorHandler the error handler.
*/
public void setErrorHandler(ServiceBusErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
} | class ServiceBusMessageListenerContainer extends AbstractMessageListenerContainer {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceBusMessageListenerContainer.class);
private final ServiceBusProcessorFactory processorFactory;
private final ServiceBusContainerProperties containerProperties;
private ServiceBusErrorHandler errorHandler;
private ServiceBusProcessorClient delegate;
/**
* Create an instance using the supplied processor factory and container properties.
*
* @param processorFactory the processor factory.
* @param containerProperties the container properties.
*/
public ServiceBusMessageListenerContainer(ServiceBusProcessorFactory processorFactory,
ServiceBusContainerProperties containerProperties) {
this.processorFactory = processorFactory;
this.containerProperties = containerProperties == null ? new ServiceBusContainerProperties() : containerProperties;
}
@Override
protected void doStart() {
String entityName = containerProperties.getEntityName();
String subscriptionName = containerProperties.getSubscriptionName();
if (this.errorHandler != null) {
this.containerProperties.setErrorHandler(errorHandler);
}
if (StringUtils.hasText(subscriptionName)) {
this.delegate = this.processorFactory.createProcessor(entityName, subscriptionName, containerProperties);
} else {
this.delegate = this.processorFactory.createProcessor(entityName, containerProperties);
}
this.delegate.start();
}
@Override
@Override
public void setupMessageListener(Object messageListener) {
this.containerProperties.setMessageListener((ServiceBusMessageListener) messageListener);
}
@Override
public ServiceBusContainerProperties getContainerProperties() {
return containerProperties;
}
/**
* Set the error handler to call when the listener throws an exception.
* @param errorHandler the error handler.
*/
public void setErrorHandler(ServiceBusErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
} |
Is it possible to use a smaller VM size (D8 seems 8-core?) for test, or this is already the smallest? | public void canCreateVirtualMachineWithEphemeralOSDisk() {
VirtualMachine vm = computeManager.virtualMachines()
.define(vmName)
.withRegion(Region.US_WEST3)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.withSize(VirtualMachineSizeTypes.STANDARD_D8S_V3)
.withEphemeralOSDisk()
.withPlacement(DiffDiskPlacement.CACHE_DISK)
.withNewDataDisk(1, 1, CachingTypes.READ_WRITE)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.create();
Assertions.assertNull(vm.osDiskDiskEncryptionSetId());
Assertions.assertTrue(vm.osDiskSize() > 0);
Assertions.assertEquals(vm.osDiskDeleteOptions(), DeleteOptions.DELETE);
Assertions.assertEquals(vm.osDiskCachingType(), CachingTypes.READ_ONLY);
Assertions.assertFalse(CoreUtils.isNullOrEmpty(vm.dataDisks()));
Assertions.assertTrue(vm.osDiskIsEphemeral());
Assertions.assertNotNull(vm.osDiskId());
String osDiskId = vm.osDiskId();
vm.update()
.withoutDataDisk(1)
.withNewDataDisk(1, 2, CachingTypes.NONE)
.withNewDataDisk(1)
.apply();
Assertions.assertEquals(vm.dataDisks().size(), 2);
vm.powerOff();
vm.start();
vm.refresh();
Assertions.assertEquals(osDiskId, vm.osDiskId());
Assertions.assertThrows(Exception.class, vm::deallocate);
} | .withSize(VirtualMachineSizeTypes.STANDARD_D8S_V3) | public void canCreateVirtualMachineWithEphemeralOSDisk() {
VirtualMachine vm = computeManager.virtualMachines()
.define(vmName)
.withRegion(Region.US_WEST3)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2)
.withEphemeralOSDisk()
.withPlacement(DiffDiskPlacement.CACHE_DISK)
.withNewDataDisk(1, 1, CachingTypes.READ_WRITE)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.create();
Assertions.assertNull(vm.osDiskDiskEncryptionSetId());
Assertions.assertTrue(vm.osDiskSize() > 0);
Assertions.assertEquals(vm.osDiskDeleteOptions(), DeleteOptions.DELETE);
Assertions.assertEquals(vm.osDiskCachingType(), CachingTypes.READ_ONLY);
Assertions.assertFalse(CoreUtils.isNullOrEmpty(vm.dataDisks()));
Assertions.assertTrue(vm.isOSDiskEphemeral());
Assertions.assertNotNull(vm.osDiskId());
String osDiskId = vm.osDiskId();
vm.update()
.withoutDataDisk(1)
.withNewDataDisk(1, 2, CachingTypes.NONE)
.withNewDataDisk(1)
.apply();
Assertions.assertEquals(vm.dataDisks().size(), 2);
vm.powerOff();
vm.start();
vm.refresh();
Assertions.assertEquals(osDiskId, vm.osDiskId());
Assertions.assertThrows(Exception.class, vm::deallocate);
} | class VirtualMachineOperationsTests extends ComputeManagementTest {
private String rgName = "";
private String rgName2 = "";
private final Region region = Region.US_EAST;
private final Region regionProxPlacementGroup = Region.US_WEST;
private final Region regionProxPlacementGroup2 = Region.US_EAST;
private final String vmName = "javavm";
private final String proxGroupName = "testproxgroup1";
private final String proxGroupName2 = "testproxgroup2";
private final String availabilitySetName = "availset1";
private final String availabilitySetName2 = "availset2";
private final ProximityPlacementGroupType proxGroupType = ProximityPlacementGroupType.STANDARD;
@Override
protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) {
rgName = generateRandomResourceName("javacsmrg", 15);
rgName2 = generateRandomResourceName("javacsmrg2", 15);
super.initializeClients(httpPipeline, profile);
}
@Override
protected void cleanUpResources() {
if (rgName != null) {
resourceManager.resourceGroups().beginDeleteByName(rgName);
}
}
@Test
public void canCreateVirtualMachineWithNetworking() throws Exception {
NetworkSecurityGroup nsg =
this
.networkManager
.networkSecurityGroups()
.define("nsg")
.withRegion(region)
.withNewResourceGroup(rgName)
.defineRule("rule1")
.allowInbound()
.fromAnyAddress()
.fromPort(80)
.toAnyAddress()
.toPort(80)
.withProtocol(SecurityRuleProtocol.TCP)
.attach()
.create();
Creatable<Network> networkDefinition =
this
.networkManager
.networks()
.define("network1")
.withRegion(region)
.withNewResourceGroup(rgName)
.withAddressSpace("10.0.0.0/28")
.defineSubnet("subnet1")
.withAddressPrefix("10.0.0.0/29")
.withExistingNetworkSecurityGroup(nsg)
.attach();
VirtualMachine vm =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork(networkDefinition)
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.create();
NetworkInterface primaryNic = vm.getPrimaryNetworkInterface();
Assertions.assertNotNull(primaryNic);
NicIpConfiguration primaryIpConfig = primaryNic.primaryIPConfiguration();
Assertions.assertNotNull(primaryIpConfig);
Assertions.assertNotNull(primaryIpConfig.networkId());
Network network = primaryIpConfig.getNetwork();
Assertions.assertNotNull(primaryIpConfig.subnetName());
Subnet subnet = network.subnets().get(primaryIpConfig.subnetName());
Assertions.assertNotNull(subnet);
nsg = subnet.getNetworkSecurityGroup();
Assertions.assertNotNull(nsg);
Assertions.assertEquals("nsg", nsg.name());
Assertions.assertEquals(1, nsg.securityRules().size());
nsg = primaryIpConfig.getNetworkSecurityGroup();
Assertions.assertEquals("nsg", nsg.name());
}
@Test
public void canCreateVirtualMachine() throws Exception {
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLicenseType("Windows_Server")
.create();
VirtualMachine foundVM = null;
PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName);
for (VirtualMachine vm1 : vms) {
if (vm1.name().equals(vmName)) {
foundVM = vm1;
break;
}
}
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(region, foundVM.region());
foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(region, foundVM.region());
Assertions.assertEquals("Windows_Server", foundVM.licenseType());
PowerState powerState = foundVM.powerState();
Assertions.assertEquals(powerState, PowerState.RUNNING);
VirtualMachineInstanceView instanceView = foundVM.instanceView();
Assertions.assertNotNull(instanceView);
Assertions.assertNotNull(instanceView.statuses().size() > 0);
computeManager.virtualMachines().deleteById(foundVM.id());
}
@Test
public void cannotCreateVirtualMachineSyncPoll() throws Exception {
final String mySqlInstallScript = "https:
final String installCommand = "bash install_mysql_server_5.6.sh Abc.123x(";
Assertions.assertThrows(IllegalStateException.class, () -> {
Accepted<VirtualMachine> acceptedVirtualMachine =
this.computeManager.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.defineNewExtension("CustomScriptForLinux")
.withPublisher("Microsoft.OSTCExtensions")
.withType("CustomScriptForLinux")
.withVersion("1.4")
.withMinorVersionAutoUpgrade()
.withPublicSetting("fileUris", Collections.singletonList(mySqlInstallScript))
.withPublicSetting("commandToExecute", installCommand)
.attach()
.beginCreate();
});
boolean dependentResourceCreated = computeManager.resourceManager().serviceClient().getResourceGroups().checkExistence(rgName);
Assertions.assertFalse(dependentResourceCreated);
rgName = null;
}
@Test
public void canCreateVirtualMachineSyncPoll() throws Exception {
final long defaultDelayInMillis = 10 * 1000;
Accepted<VirtualMachine> acceptedVirtualMachine = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLicenseType("Windows_Server")
.beginCreate();
VirtualMachine createdVirtualMachine = acceptedVirtualMachine.getActivationResponse().getValue();
Assertions.assertNotEquals("Succeeded", createdVirtualMachine.provisioningState());
LongRunningOperationStatus pollStatus = acceptedVirtualMachine.getActivationResponse().getStatus();
long delayInMills = acceptedVirtualMachine.getActivationResponse().getRetryAfter() == null
? defaultDelayInMillis
: acceptedVirtualMachine.getActivationResponse().getRetryAfter().toMillis();
while (!pollStatus.isComplete()) {
ResourceManagerUtils.sleep(Duration.ofMillis(delayInMills));
PollResponse<?> pollResponse = acceptedVirtualMachine.getSyncPoller().poll();
pollStatus = pollResponse.getStatus();
delayInMills = pollResponse.getRetryAfter() == null
? defaultDelayInMillis
: pollResponse.getRetryAfter().toMillis();
}
Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollStatus);
VirtualMachine virtualMachine = acceptedVirtualMachine.getFinalResult();
Assertions.assertEquals("Succeeded", virtualMachine.provisioningState());
Accepted<Void> acceptedDelete = computeManager.virtualMachines()
.beginDeleteByResourceGroup(virtualMachine.resourceGroupName(), virtualMachine.name());
pollStatus = acceptedDelete.getActivationResponse().getStatus();
delayInMills = acceptedDelete.getActivationResponse().getRetryAfter() == null
? defaultDelayInMillis
: (int) acceptedDelete.getActivationResponse().getRetryAfter().toMillis();
while (!pollStatus.isComplete()) {
ResourceManagerUtils.sleep(Duration.ofMillis(delayInMills));
PollResponse<?> pollResponse = acceptedDelete.getSyncPoller().poll();
pollStatus = pollResponse.getStatus();
delayInMills = pollResponse.getRetryAfter() == null
? defaultDelayInMillis
: (int) pollResponse.getRetryAfter().toMillis();
}
boolean deleted = false;
try {
computeManager.virtualMachines().getById(virtualMachine.id());
} catch (ManagementException e) {
if (e.getResponse().getStatusCode() == 404
&& ("NotFound".equals(e.getValue().getCode()) || "ResourceNotFound".equals(e.getValue().getCode()))) {
deleted = true;
}
}
Assertions.assertTrue(deleted);
}
@Test
public void canCreateUpdatePriorityAndPrice() throws Exception {
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLowPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE)
.withMaxPrice(1000.0)
.withLicenseType("Windows_Server")
.create();
VirtualMachine foundVM = null;
PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName);
for (VirtualMachine vm1 : vms) {
if (vm1.name().equals(vmName)) {
foundVM = vm1;
break;
}
}
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(region, foundVM.region());
foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(region, foundVM.region());
Assertions.assertEquals("Windows_Server", foundVM.licenseType());
Assertions.assertEquals((Double) 1000.0, foundVM.billingProfile().maxPrice());
Assertions.assertEquals(VirtualMachineEvictionPolicyTypes.DEALLOCATE, foundVM.evictionPolicy());
try {
foundVM.update().withMaxPrice(1500.0).apply();
Assertions.assertEquals((Double) 1500.0, foundVM.billingProfile().maxPrice());
Assertions.fail();
} catch (ManagementException e) {
}
foundVM.deallocate();
foundVM.update().withMaxPrice(2000.0).apply();
foundVM.start();
Assertions.assertEquals((Double) 2000.0, foundVM.billingProfile().maxPrice());
foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.SPOT).apply();
Assertions.assertEquals(VirtualMachinePriorityTypes.SPOT, foundVM.priority());
foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.LOW).apply();
Assertions.assertEquals(VirtualMachinePriorityTypes.LOW, foundVM.priority());
try {
foundVM.update().withPriority(VirtualMachinePriorityTypes.REGULAR).apply();
Assertions.assertEquals(VirtualMachinePriorityTypes.REGULAR, foundVM.priority());
Assertions.fail();
} catch (ManagementException e) {
}
computeManager.virtualMachines().deleteById(foundVM.id());
}
@Test
public void cannotUpdateProximityPlacementGroupForVirtualMachine() throws Exception {
AvailabilitySet setCreated =
computeManager
.availabilitySets()
.define(availabilitySetName)
.withRegion(regionProxPlacementGroup)
.withNewResourceGroup(rgName)
.withNewProximityPlacementGroup(proxGroupName, proxGroupType)
.create();
Assertions.assertEquals(availabilitySetName, setCreated.name());
Assertions.assertNotNull(setCreated.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location());
AvailabilitySet setCreated2 =
computeManager
.availabilitySets()
.define(availabilitySetName2)
.withRegion(regionProxPlacementGroup2)
.withNewResourceGroup(rgName2)
.withNewProximityPlacementGroup(proxGroupName2, proxGroupType)
.create();
Assertions.assertEquals(availabilitySetName2, setCreated2.name());
Assertions.assertNotNull(setCreated2.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, setCreated2.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(setCreated2.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(setCreated2.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated2.id().equalsIgnoreCase(setCreated2.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertEquals(setCreated2.regionName(), setCreated2.proximityPlacementGroup().location());
computeManager
.virtualMachines()
.define(vmName)
.withRegion(regionProxPlacementGroup)
.withExistingResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withProximityPlacementGroup(setCreated.proximityPlacementGroup().id())
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLicenseType("Windows_Server")
.create();
VirtualMachine foundVM = null;
PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName);
for (VirtualMachine vm1 : vms) {
if (vm1.name().equals(vmName)) {
foundVM = vm1;
break;
}
}
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(regionProxPlacementGroup, foundVM.region());
foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(regionProxPlacementGroup, foundVM.region());
Assertions.assertEquals("Windows_Server", foundVM.licenseType());
PowerState powerState = foundVM.powerState();
Assertions.assertEquals(powerState, PowerState.RUNNING);
VirtualMachineInstanceView instanceView = foundVM.instanceView();
Assertions.assertNotNull(instanceView);
Assertions.assertNotNull(instanceView.statuses().size() > 0);
Assertions.assertNotNull(foundVM.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds());
Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty());
Assertions
.assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0)));
try {
VirtualMachine updatedVm =
foundVM.update().withProximityPlacementGroup(setCreated2.proximityPlacementGroup().id()).apply();
} catch (ManagementException clEx) {
Assertions
.assertTrue(
clEx
.getMessage()
.contains(
"Updating proximity placement group of VM javavm is not allowed while the VM is running."
+ " Please stop/deallocate the VM and retry the operation."));
}
computeManager.virtualMachines().deleteById(foundVM.id());
computeManager.availabilitySets().deleteById(setCreated.id());
}
@Test
public void canCreateVirtualMachinesAndAvailabilitySetInSameProximityPlacementGroup() throws Exception {
AvailabilitySet setCreated =
computeManager
.availabilitySets()
.define(availabilitySetName)
.withRegion(regionProxPlacementGroup)
.withNewResourceGroup(rgName)
.withNewProximityPlacementGroup(proxGroupName, proxGroupType)
.create();
Assertions.assertEquals(availabilitySetName, setCreated.name());
Assertions.assertNotNull(setCreated.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location());
computeManager
.virtualMachines()
.define(vmName)
.withRegion(regionProxPlacementGroup)
.withExistingResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withProximityPlacementGroup(setCreated.proximityPlacementGroup().id())
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLicenseType("Windows_Server")
.create();
VirtualMachine foundVM = null;
PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName);
for (VirtualMachine vm1 : vms) {
if (vm1.name().equals(vmName)) {
foundVM = vm1;
break;
}
}
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(regionProxPlacementGroup, foundVM.region());
foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(regionProxPlacementGroup, foundVM.region());
Assertions.assertEquals("Windows_Server", foundVM.licenseType());
PowerState powerState = foundVM.powerState();
Assertions.assertEquals(powerState, PowerState.RUNNING);
VirtualMachineInstanceView instanceView = foundVM.instanceView();
Assertions.assertNotNull(instanceView);
Assertions.assertNotNull(instanceView.statuses().size() > 0);
Assertions.assertNotNull(foundVM.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds());
Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty());
Assertions
.assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0)));
VirtualMachine updatedVm = foundVM.update().withoutProximityPlacementGroup().apply();
Assertions.assertNotNull(updatedVm.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, updatedVm.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(updatedVm.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(updatedVm.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(updatedVm.proximityPlacementGroup().availabilitySetIds().get(0)));
computeManager.virtualMachines().deleteById(foundVM.id());
computeManager.availabilitySets().deleteById(setCreated.id());
}
@Test
public void canCreateVirtualMachinesAndRelatedResourcesInParallel() throws Exception {
String vmNamePrefix = "vmz";
String publicIpNamePrefix = generateRandomResourceName("pip-", 15);
String networkNamePrefix = generateRandomResourceName("vnet-", 15);
int count = 5;
CreatablesInfo creatablesInfo =
prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count);
List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables;
List<String> networkCreatableKeys = creatablesInfo.networkCreatableKeys;
List<String> publicIpCreatableKeys = creatablesInfo.publicIpCreatableKeys;
CreatedResources<VirtualMachine> createdVirtualMachines =
computeManager.virtualMachines().create(virtualMachineCreatables);
Assertions.assertTrue(createdVirtualMachines.size() == count);
Set<String> virtualMachineNames = new HashSet<>();
for (int i = 0; i < count; i++) {
virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i));
}
for (VirtualMachine virtualMachine : createdVirtualMachines.values()) {
Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name()));
Assertions.assertNotNull(virtualMachine.id());
}
Set<String> networkNames = new HashSet<>();
for (int i = 0; i < count; i++) {
networkNames.add(String.format("%s-%d", networkNamePrefix, i));
}
for (String networkCreatableKey : networkCreatableKeys) {
Network createdNetwork = (Network) createdVirtualMachines.createdRelatedResource(networkCreatableKey);
Assertions.assertNotNull(createdNetwork);
Assertions.assertTrue(networkNames.contains(createdNetwork.name()));
}
Set<String> publicIPAddressNames = new HashSet<>();
for (int i = 0; i < count; i++) {
publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i));
}
for (String publicIpCreatableKey : publicIpCreatableKeys) {
PublicIpAddress createdPublicIpAddress =
(PublicIpAddress) createdVirtualMachines.createdRelatedResource(publicIpCreatableKey);
Assertions.assertNotNull(createdPublicIpAddress);
Assertions.assertTrue(publicIPAddressNames.contains(createdPublicIpAddress.name()));
}
}
@Test
public void canStreamParallelCreatedVirtualMachinesAndRelatedResources() throws Exception {
String vmNamePrefix = "vmz";
String publicIpNamePrefix = generateRandomResourceName("pip-", 15);
String networkNamePrefix = generateRandomResourceName("vnet-", 15);
int count = 5;
final Set<String> virtualMachineNames = new HashSet<>();
for (int i = 0; i < count; i++) {
virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i));
}
final Set<String> networkNames = new HashSet<>();
for (int i = 0; i < count; i++) {
networkNames.add(String.format("%s-%d", networkNamePrefix, i));
}
final Set<String> publicIPAddressNames = new HashSet<>();
for (int i = 0; i < count; i++) {
publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i));
}
final CreatablesInfo creatablesInfo =
prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count);
final AtomicInteger resourceCount = new AtomicInteger(0);
List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables;
computeManager
.virtualMachines()
.createAsync(virtualMachineCreatables)
.map(
createdResource -> {
if (createdResource instanceof Resource) {
Resource resource = (Resource) createdResource;
System.out.println("Created: " + resource.id());
if (resource instanceof VirtualMachine) {
VirtualMachine virtualMachine = (VirtualMachine) resource;
Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name()));
Assertions.assertNotNull(virtualMachine.id());
} else if (resource instanceof Network) {
Network network = (Network) resource;
Assertions.assertTrue(networkNames.contains(network.name()));
Assertions.assertNotNull(network.id());
} else if (resource instanceof PublicIpAddress) {
PublicIpAddress publicIPAddress = (PublicIpAddress) resource;
Assertions.assertTrue(publicIPAddressNames.contains(publicIPAddress.name()));
Assertions.assertNotNull(publicIPAddress.id());
}
}
resourceCount.incrementAndGet();
return createdResource;
})
.blockLast();
networkNames.forEach(name -> {
Assertions.assertNotNull(networkManager.networks().getByResourceGroup(rgName, name));
});
publicIPAddressNames.forEach(name -> {
Assertions.assertNotNull(networkManager.publicIpAddresses().getByResourceGroup(rgName, name));
});
Assertions.assertEquals(1, storageManager.storageAccounts().listByResourceGroup(rgName).stream().count());
Assertions.assertEquals(count, networkManager.networkInterfaces().listByResourceGroup(rgName).stream().count());
Assertions.assertEquals(count, resourceCount.get());
}
@Test
public void canSetStorageAccountForUnmanagedDisk() {
final String storageName = generateRandomResourceName("st", 14);
StorageAccount storageAccount =
storageManager
.storageAccounts()
.define(storageName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withSku(StorageAccountSkuType.PREMIUM_LRS)
.create();
VirtualMachine virtualMachine =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.withUnmanagedDisks()
.defineUnmanagedDataDisk("disk1")
.withNewVhd(100)
.withLun(2)
.storeAt(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd")
.attach()
.defineUnmanagedDataDisk("disk2")
.withNewVhd(100)
.withLun(3)
.storeAt(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd")
.attach()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.create();
Map<Integer, VirtualMachineUnmanagedDataDisk> unmanagedDataDisks = virtualMachine.unmanagedDataDisks();
Assertions.assertNotNull(unmanagedDataDisks);
Assertions.assertEquals(2, unmanagedDataDisks.size());
VirtualMachineUnmanagedDataDisk firstUnmanagedDataDisk = unmanagedDataDisks.get(2);
Assertions.assertNotNull(firstUnmanagedDataDisk);
VirtualMachineUnmanagedDataDisk secondUnmanagedDataDisk = unmanagedDataDisks.get(3);
Assertions.assertNotNull(secondUnmanagedDataDisk);
String createdVhdUri1 = firstUnmanagedDataDisk.vhdUri();
String createdVhdUri2 = secondUnmanagedDataDisk.vhdUri();
Assertions.assertNotNull(createdVhdUri1);
Assertions.assertNotNull(createdVhdUri2);
computeManager.virtualMachines().deleteById(virtualMachine.id());
virtualMachine =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.withUnmanagedDisks()
.withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd")
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4"))
.create();
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
unmanagedDataDisks = virtualMachine.unmanagedDataDisks();
Assertions.assertNotNull(unmanagedDataDisks);
Assertions.assertEquals(1, unmanagedDataDisks.size());
firstUnmanagedDataDisk = null;
for (VirtualMachineUnmanagedDataDisk unmanagedDisk : unmanagedDataDisks.values()) {
firstUnmanagedDataDisk = unmanagedDisk;
break;
}
Assertions.assertNotNull(firstUnmanagedDataDisk.vhdUri());
Assertions.assertTrue(firstUnmanagedDataDisk.vhdUri().equalsIgnoreCase(createdVhdUri1));
virtualMachine
.update()
.withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd")
.apply();
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
unmanagedDataDisks = virtualMachine.unmanagedDataDisks();
Assertions.assertNotNull(unmanagedDataDisks);
Assertions.assertEquals(2, unmanagedDataDisks.size());
}
@Test
public void canUpdateTagsOnVM() {
VirtualMachine virtualMachine =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("firstuser")
.withSsh(sshPublicKey())
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.create();
virtualMachine.update().withTag("test", "testValue").apply();
Assertions.assertEquals("testValue", virtualMachine.innerModel().tags().get("test"));
Map<String, String> testTags = new HashMap<String, String>();
testTags.put("testTag", "testValue");
virtualMachine.update().withTags(testTags).apply();
Assertions.assertEquals(testTags.get("testTag"), virtualMachine.innerModel().tags().get("testTag"));
}
@Test
public void canRunScriptOnVM() {
VirtualMachine virtualMachine =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("firstuser")
.withSsh(sshPublicKey())
.create();
List<String> installGit = new ArrayList<>();
installGit.add("sudo apt-get update");
installGit.add("sudo apt-get install -y git");
RunCommandResult runResult =
virtualMachine.runShellScript(installGit, new ArrayList<RunCommandInputParameter>());
Assertions.assertNotNull(runResult);
Assertions.assertNotNull(runResult.value());
Assertions.assertTrue(runResult.value().size() > 0);
}
@Test
@DoNotRecord(skipInPlayback = true)
public void canPerformSimulateEvictionOnSpotVirtualMachine() {
VirtualMachine virtualMachine = computeManager.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("firstuser")
.withSsh(sshPublicKey())
.withSpotPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE)
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.create();
Assertions.assertNotNull(virtualMachine.osDiskStorageAccountType());
Assertions.assertTrue(virtualMachine.osDiskSize() > 0);
Disk disk = computeManager.disks().getById(virtualMachine.osDiskId());
Assertions.assertNotNull(disk);
Assertions.assertEquals(DiskState.ATTACHED, disk.innerModel().diskState());
virtualMachine.simulateEviction();
boolean deallocated = false;
int pollIntervalInMinutes = 5;
for (int i = 0; i < 30; i += pollIntervalInMinutes) {
ResourceManagerUtils.sleep(Duration.ofMinutes(pollIntervalInMinutes));
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
if (virtualMachine.powerState() == PowerState.DEALLOCATED) {
deallocated = true;
break;
}
}
Assertions.assertTrue(deallocated);
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
Assertions.assertNotNull(virtualMachine);
Assertions.assertNull(virtualMachine.osDiskStorageAccountType());
Assertions.assertEquals(0, virtualMachine.osDiskSize());
disk = computeManager.disks().getById(virtualMachine.osDiskId());
Assertions.assertEquals(DiskState.RESERVED, disk.innerModel().diskState());
}
@Test
public void canForceDeleteVirtualMachine() {
computeManager.virtualMachines()
.define(vmName)
.withRegion("eastus2euap")
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.create();
VirtualMachine virtualMachine = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(virtualMachine);
Assertions.assertEquals(Region.fromName("eastus2euap"), virtualMachine.region());
String nicId = virtualMachine.primaryNetworkInterfaceId();
computeManager.virtualMachines().deleteById(virtualMachine.id(), true);
try {
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
} catch (ManagementException ex) {
virtualMachine = null;
Assertions.assertEquals(404, ex.getResponse().getStatusCode());
}
Assertions.assertNull(virtualMachine);
NetworkInterface nic = networkManager.networkInterfaces().getById(nicId);
Assertions.assertNotNull(nic);
}
@Test
public void canCreateVirtualMachineWithDeleteOption() throws Exception {
Region region = Region.US_WEST2;
final String publicIpDnsLabel = generateRandomResourceName("pip", 20);
Network network = this
.networkManager
.networks()
.define("network1")
.withRegion(region)
.withNewResourceGroup(rgName)
.withAddressSpace("10.0.0.0/24")
.withSubnet("default", "10.0.0.0/24")
.create();
VirtualMachine vm1 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withNewPrimaryPublicIPAddress(publicIpDnsLabel/*, DeleteOptions.DELETE*/)
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withNewDataDisk(10)
.withNewDataDisk(computeManager.disks()
.define("datadisk2")
.withRegion(region)
.withExistingResourceGroup(rgName)
.withData()
.withSizeInGB(10))
.withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE)
.withOSDiskDeleteOptions(DeleteOptions.DELETE)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
Assertions.assertEquals(DeleteOptions.DELETE, vm1.osDiskDeleteOptions());
Assertions.assertEquals(DeleteOptions.DELETE, vm1.dataDisks().get(0).deleteOptions());
Assertions.assertEquals(DeleteOptions.DELETE, vm1.dataDisks().get(1).deleteOptions());
Assertions.assertEquals(vm1.id(), computeManager.virtualMachines().getById(vm1.id()).id());
computeManager.virtualMachines().deleteById(vm1.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(2, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count());
PublicIpAddress publicIpAddress = computeManager.networkManager().publicIpAddresses().listByResourceGroup(rgName).stream().findFirst().get();
computeManager.networkManager().publicIpAddresses().deleteById(publicIpAddress.id());
String secondaryNicName = generateRandomResourceName("nic", 10);
Creatable<NetworkInterface> secondaryNetworkInterfaceCreatable =
this
.networkManager
.networkInterfaces()
.define(secondaryNicName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic();
VirtualMachine vm2 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withOSDiskDeleteOptions(DeleteOptions.DELETE)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable, DeleteOptions.DELETE)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
computeManager.virtualMachines().deleteById(vm2.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(1, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count());
secondaryNetworkInterfaceCreatable =
this
.networkManager
.networkInterfaces()
.define(secondaryNicName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic();
VirtualMachine vm3 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withNewDataDisk(10)
.withNewDataDisk(computeManager.disks()
.define("datadisk2")
.withRegion(region)
.withExistingResourceGroup(rgName)
.withData()
.withSizeInGB(10))
.withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
Assertions.assertEquals(DeleteOptions.DETACH, vm3.osDiskDeleteOptions());
Assertions.assertEquals(DeleteOptions.DETACH, vm3.dataDisks().get(0).deleteOptions());
Assertions.assertEquals(DeleteOptions.DETACH, vm3.dataDisks().get(1).deleteOptions());
computeManager.virtualMachines().deleteById(vm3.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(3, computeManager.disks().listByResourceGroup(rgName).stream().count());
Assertions.assertEquals(2, computeManager.networkManager().networkInterfaces().listByResourceGroup(rgName).stream().count());
}
@Test
public void canUpdateVirtualMachineWithDeleteOption() throws Exception {
Region region = Region.US_WEST2;
Network network = this
.networkManager
.networks()
.define("network1")
.withRegion(region)
.withNewResourceGroup(rgName)
.withAddressSpace("10.0.0.0/24")
.withSubnet("default", "10.0.0.0/24")
.create();
VirtualMachine vm1 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withNewDataDisk(10)
.withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE)
.withOSDiskDeleteOptions(DeleteOptions.DELETE)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
vm1.update()
.withNewDataDisk(10)
.apply();
computeManager.virtualMachines().deleteById(vm1.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(1, computeManager.disks().listByResourceGroup(rgName).stream().count());
Disk disk = computeManager.disks().listByResourceGroup(rgName).stream().findFirst().get();
computeManager.disks().deleteById(disk.id());
VirtualMachine vm2 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withNewDataDisk(10)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
vm2.update()
.withNewDataDisk(10)
.withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE)
.apply();
computeManager.virtualMachines().deleteById(vm2.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(2, computeManager.disks().listByResourceGroup(rgName).stream().count());
}
@Test
public void canHibernateVirtualMachine() {
VirtualMachine vm = computeManager.virtualMachines()
.define(vmName)
.withRegion("eastus2euap")
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withSize(VirtualMachineSizeTypes.STANDARD_D2S_V3)
.enableHibernation()
.create();
Assertions.assertTrue(vm.isHibernationEnabled());
vm.deallocate(true);
InstanceViewStatus hibernationStatus = vm.instanceView().statuses().stream()
.filter(status -> "HibernationState/Hibernated".equals(status.code()))
.findFirst().orElse(null);
Assertions.assertNotNull(hibernationStatus);
vm.start();
vm.deallocate();
vm.update()
.disableHibernation()
.apply();
Assertions.assertFalse(vm.isHibernationEnabled());
}
@Test
public void canOperateVirtualMachine() {
VirtualMachine vm = computeManager.virtualMachines()
.define(vmName)
.withRegion(Region.US_WEST3)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
Assertions.assertEquals(PowerState.RUNNING, vm.powerState());
vm.redeploy();
vm.powerOff(true);
vm.refreshInstanceView();
Assertions.assertEquals(PowerState.STOPPED, vm.powerState());
vm.start();
vm.refreshInstanceView();
Assertions.assertEquals(PowerState.RUNNING, vm.powerState());
vm.restart();
vm.refreshInstanceView();
Assertions.assertEquals(PowerState.RUNNING, vm.powerState());
vm.deallocate();
vm.refreshInstanceView();
Assertions.assertEquals(PowerState.DEALLOCATED, vm.powerState());
}
@Test
private CreatablesInfo prepareCreatableVirtualMachines(
Region region, String vmNamePrefix, String networkNamePrefix, String publicIpNamePrefix, int vmCount) {
Creatable<ResourceGroup> resourceGroupCreatable =
resourceManager.resourceGroups().define(rgName).withRegion(region);
Creatable<StorageAccount> storageAccountCreatable =
storageManager
.storageAccounts()
.define(generateRandomResourceName("stg", 20))
.withRegion(region)
.withNewResourceGroup(resourceGroupCreatable);
List<String> networkCreatableKeys = new ArrayList<>();
List<String> publicIpCreatableKeys = new ArrayList<>();
List<Creatable<VirtualMachine>> virtualMachineCreatables = new ArrayList<>();
for (int i = 0; i < vmCount; i++) {
Creatable<Network> networkCreatable =
networkManager
.networks()
.define(String.format("%s-%d", networkNamePrefix, i))
.withRegion(region)
.withNewResourceGroup(resourceGroupCreatable)
.withAddressSpace("10.0.0.0/28");
networkCreatableKeys.add(networkCreatable.key());
Creatable<PublicIpAddress> publicIPAddressCreatable =
networkManager
.publicIpAddresses()
.define(String.format("%s-%d", publicIpNamePrefix, i))
.withRegion(region)
.withNewResourceGroup(resourceGroupCreatable);
publicIpCreatableKeys.add(publicIPAddressCreatable.key());
Creatable<VirtualMachine> virtualMachineCreatable =
computeManager
.virtualMachines()
.define(String.format("%s-%d", vmNamePrefix, i))
.withRegion(region)
.withNewResourceGroup(resourceGroupCreatable)
.withNewPrimaryNetwork(networkCreatable)
.withPrimaryPrivateIPAddressDynamic()
.withNewPrimaryPublicIPAddress(publicIPAddressCreatable)
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("tirekicker")
.withSsh(sshPublicKey())
.withUnmanagedDisks()
.withNewStorageAccount(storageAccountCreatable);
virtualMachineCreatables.add(virtualMachineCreatable);
}
CreatablesInfo creatablesInfo = new CreatablesInfo();
creatablesInfo.virtualMachineCreatables = virtualMachineCreatables;
creatablesInfo.networkCreatableKeys = networkCreatableKeys;
creatablesInfo.publicIpCreatableKeys = publicIpCreatableKeys;
return creatablesInfo;
}
class CreatablesInfo {
private List<Creatable<VirtualMachine>> virtualMachineCreatables;
List<String> networkCreatableKeys;
List<String> publicIpCreatableKeys;
}
} | class VirtualMachineOperationsTests extends ComputeManagementTest {
private String rgName = "";
private String rgName2 = "";
private final Region region = Region.US_EAST;
private final Region regionProxPlacementGroup = Region.US_WEST;
private final Region regionProxPlacementGroup2 = Region.US_EAST;
private final String vmName = "javavm";
private final String proxGroupName = "testproxgroup1";
private final String proxGroupName2 = "testproxgroup2";
private final String availabilitySetName = "availset1";
private final String availabilitySetName2 = "availset2";
private final ProximityPlacementGroupType proxGroupType = ProximityPlacementGroupType.STANDARD;
@Override
protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) {
rgName = generateRandomResourceName("javacsmrg", 15);
rgName2 = generateRandomResourceName("javacsmrg2", 15);
super.initializeClients(httpPipeline, profile);
}
@Override
protected void cleanUpResources() {
if (rgName != null) {
resourceManager.resourceGroups().beginDeleteByName(rgName);
}
}
@Test
public void canCreateVirtualMachineWithNetworking() throws Exception {
NetworkSecurityGroup nsg =
this
.networkManager
.networkSecurityGroups()
.define("nsg")
.withRegion(region)
.withNewResourceGroup(rgName)
.defineRule("rule1")
.allowInbound()
.fromAnyAddress()
.fromPort(80)
.toAnyAddress()
.toPort(80)
.withProtocol(SecurityRuleProtocol.TCP)
.attach()
.create();
Creatable<Network> networkDefinition =
this
.networkManager
.networks()
.define("network1")
.withRegion(region)
.withNewResourceGroup(rgName)
.withAddressSpace("10.0.0.0/28")
.defineSubnet("subnet1")
.withAddressPrefix("10.0.0.0/29")
.withExistingNetworkSecurityGroup(nsg)
.attach();
VirtualMachine vm =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork(networkDefinition)
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.create();
NetworkInterface primaryNic = vm.getPrimaryNetworkInterface();
Assertions.assertNotNull(primaryNic);
NicIpConfiguration primaryIpConfig = primaryNic.primaryIPConfiguration();
Assertions.assertNotNull(primaryIpConfig);
Assertions.assertNotNull(primaryIpConfig.networkId());
Network network = primaryIpConfig.getNetwork();
Assertions.assertNotNull(primaryIpConfig.subnetName());
Subnet subnet = network.subnets().get(primaryIpConfig.subnetName());
Assertions.assertNotNull(subnet);
nsg = subnet.getNetworkSecurityGroup();
Assertions.assertNotNull(nsg);
Assertions.assertEquals("nsg", nsg.name());
Assertions.assertEquals(1, nsg.securityRules().size());
nsg = primaryIpConfig.getNetworkSecurityGroup();
Assertions.assertEquals("nsg", nsg.name());
}
@Test
public void canCreateVirtualMachine() throws Exception {
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLicenseType("Windows_Server")
.create();
VirtualMachine foundVM = null;
PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName);
for (VirtualMachine vm1 : vms) {
if (vm1.name().equals(vmName)) {
foundVM = vm1;
break;
}
}
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(region, foundVM.region());
foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(region, foundVM.region());
Assertions.assertEquals("Windows_Server", foundVM.licenseType());
PowerState powerState = foundVM.powerState();
Assertions.assertEquals(powerState, PowerState.RUNNING);
VirtualMachineInstanceView instanceView = foundVM.instanceView();
Assertions.assertNotNull(instanceView);
Assertions.assertNotNull(instanceView.statuses().size() > 0);
computeManager.virtualMachines().deleteById(foundVM.id());
}
@Test
public void cannotCreateVirtualMachineSyncPoll() throws Exception {
final String mySqlInstallScript = "https:
final String installCommand = "bash install_mysql_server_5.6.sh Abc.123x(";
Assertions.assertThrows(IllegalStateException.class, () -> {
Accepted<VirtualMachine> acceptedVirtualMachine =
this.computeManager.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.defineNewExtension("CustomScriptForLinux")
.withPublisher("Microsoft.OSTCExtensions")
.withType("CustomScriptForLinux")
.withVersion("1.4")
.withMinorVersionAutoUpgrade()
.withPublicSetting("fileUris", Collections.singletonList(mySqlInstallScript))
.withPublicSetting("commandToExecute", installCommand)
.attach()
.beginCreate();
});
boolean dependentResourceCreated = computeManager.resourceManager().serviceClient().getResourceGroups().checkExistence(rgName);
Assertions.assertFalse(dependentResourceCreated);
rgName = null;
}
@Test
public void canCreateVirtualMachineSyncPoll() throws Exception {
final long defaultDelayInMillis = 10 * 1000;
Accepted<VirtualMachine> acceptedVirtualMachine = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLicenseType("Windows_Server")
.beginCreate();
VirtualMachine createdVirtualMachine = acceptedVirtualMachine.getActivationResponse().getValue();
Assertions.assertNotEquals("Succeeded", createdVirtualMachine.provisioningState());
LongRunningOperationStatus pollStatus = acceptedVirtualMachine.getActivationResponse().getStatus();
long delayInMills = acceptedVirtualMachine.getActivationResponse().getRetryAfter() == null
? defaultDelayInMillis
: acceptedVirtualMachine.getActivationResponse().getRetryAfter().toMillis();
while (!pollStatus.isComplete()) {
ResourceManagerUtils.sleep(Duration.ofMillis(delayInMills));
PollResponse<?> pollResponse = acceptedVirtualMachine.getSyncPoller().poll();
pollStatus = pollResponse.getStatus();
delayInMills = pollResponse.getRetryAfter() == null
? defaultDelayInMillis
: pollResponse.getRetryAfter().toMillis();
}
Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollStatus);
VirtualMachine virtualMachine = acceptedVirtualMachine.getFinalResult();
Assertions.assertEquals("Succeeded", virtualMachine.provisioningState());
Accepted<Void> acceptedDelete = computeManager.virtualMachines()
.beginDeleteByResourceGroup(virtualMachine.resourceGroupName(), virtualMachine.name());
pollStatus = acceptedDelete.getActivationResponse().getStatus();
delayInMills = acceptedDelete.getActivationResponse().getRetryAfter() == null
? defaultDelayInMillis
: (int) acceptedDelete.getActivationResponse().getRetryAfter().toMillis();
while (!pollStatus.isComplete()) {
ResourceManagerUtils.sleep(Duration.ofMillis(delayInMills));
PollResponse<?> pollResponse = acceptedDelete.getSyncPoller().poll();
pollStatus = pollResponse.getStatus();
delayInMills = pollResponse.getRetryAfter() == null
? defaultDelayInMillis
: (int) pollResponse.getRetryAfter().toMillis();
}
boolean deleted = false;
try {
computeManager.virtualMachines().getById(virtualMachine.id());
} catch (ManagementException e) {
if (e.getResponse().getStatusCode() == 404
&& ("NotFound".equals(e.getValue().getCode()) || "ResourceNotFound".equals(e.getValue().getCode()))) {
deleted = true;
}
}
Assertions.assertTrue(deleted);
}
@Test
public void canCreateUpdatePriorityAndPrice() throws Exception {
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLowPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE)
.withMaxPrice(1000.0)
.withLicenseType("Windows_Server")
.create();
VirtualMachine foundVM = null;
PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName);
for (VirtualMachine vm1 : vms) {
if (vm1.name().equals(vmName)) {
foundVM = vm1;
break;
}
}
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(region, foundVM.region());
foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(region, foundVM.region());
Assertions.assertEquals("Windows_Server", foundVM.licenseType());
Assertions.assertEquals((Double) 1000.0, foundVM.billingProfile().maxPrice());
Assertions.assertEquals(VirtualMachineEvictionPolicyTypes.DEALLOCATE, foundVM.evictionPolicy());
try {
foundVM.update().withMaxPrice(1500.0).apply();
Assertions.assertEquals((Double) 1500.0, foundVM.billingProfile().maxPrice());
Assertions.fail();
} catch (ManagementException e) {
}
foundVM.deallocate();
foundVM.update().withMaxPrice(2000.0).apply();
foundVM.start();
Assertions.assertEquals((Double) 2000.0, foundVM.billingProfile().maxPrice());
foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.SPOT).apply();
Assertions.assertEquals(VirtualMachinePriorityTypes.SPOT, foundVM.priority());
foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.LOW).apply();
Assertions.assertEquals(VirtualMachinePriorityTypes.LOW, foundVM.priority());
try {
foundVM.update().withPriority(VirtualMachinePriorityTypes.REGULAR).apply();
Assertions.assertEquals(VirtualMachinePriorityTypes.REGULAR, foundVM.priority());
Assertions.fail();
} catch (ManagementException e) {
}
computeManager.virtualMachines().deleteById(foundVM.id());
}
@Test
public void cannotUpdateProximityPlacementGroupForVirtualMachine() throws Exception {
AvailabilitySet setCreated =
computeManager
.availabilitySets()
.define(availabilitySetName)
.withRegion(regionProxPlacementGroup)
.withNewResourceGroup(rgName)
.withNewProximityPlacementGroup(proxGroupName, proxGroupType)
.create();
Assertions.assertEquals(availabilitySetName, setCreated.name());
Assertions.assertNotNull(setCreated.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location());
AvailabilitySet setCreated2 =
computeManager
.availabilitySets()
.define(availabilitySetName2)
.withRegion(regionProxPlacementGroup2)
.withNewResourceGroup(rgName2)
.withNewProximityPlacementGroup(proxGroupName2, proxGroupType)
.create();
Assertions.assertEquals(availabilitySetName2, setCreated2.name());
Assertions.assertNotNull(setCreated2.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, setCreated2.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(setCreated2.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(setCreated2.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated2.id().equalsIgnoreCase(setCreated2.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertEquals(setCreated2.regionName(), setCreated2.proximityPlacementGroup().location());
computeManager
.virtualMachines()
.define(vmName)
.withRegion(regionProxPlacementGroup)
.withExistingResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withProximityPlacementGroup(setCreated.proximityPlacementGroup().id())
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLicenseType("Windows_Server")
.create();
VirtualMachine foundVM = null;
PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName);
for (VirtualMachine vm1 : vms) {
if (vm1.name().equals(vmName)) {
foundVM = vm1;
break;
}
}
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(regionProxPlacementGroup, foundVM.region());
foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(regionProxPlacementGroup, foundVM.region());
Assertions.assertEquals("Windows_Server", foundVM.licenseType());
PowerState powerState = foundVM.powerState();
Assertions.assertEquals(powerState, PowerState.RUNNING);
VirtualMachineInstanceView instanceView = foundVM.instanceView();
Assertions.assertNotNull(instanceView);
Assertions.assertNotNull(instanceView.statuses().size() > 0);
Assertions.assertNotNull(foundVM.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds());
Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty());
Assertions
.assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0)));
try {
VirtualMachine updatedVm =
foundVM.update().withProximityPlacementGroup(setCreated2.proximityPlacementGroup().id()).apply();
} catch (ManagementException clEx) {
Assertions
.assertTrue(
clEx
.getMessage()
.contains(
"Updating proximity placement group of VM javavm is not allowed while the VM is running."
+ " Please stop/deallocate the VM and retry the operation."));
}
computeManager.virtualMachines().deleteById(foundVM.id());
computeManager.availabilitySets().deleteById(setCreated.id());
}
@Test
public void canCreateVirtualMachinesAndAvailabilitySetInSameProximityPlacementGroup() throws Exception {
AvailabilitySet setCreated =
computeManager
.availabilitySets()
.define(availabilitySetName)
.withRegion(regionProxPlacementGroup)
.withNewResourceGroup(rgName)
.withNewProximityPlacementGroup(proxGroupName, proxGroupType)
.create();
Assertions.assertEquals(availabilitySetName, setCreated.name());
Assertions.assertNotNull(setCreated.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location());
computeManager
.virtualMachines()
.define(vmName)
.withRegion(regionProxPlacementGroup)
.withExistingResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withProximityPlacementGroup(setCreated.proximityPlacementGroup().id())
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withOSDiskName("javatest")
.withLicenseType("Windows_Server")
.create();
VirtualMachine foundVM = null;
PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName);
for (VirtualMachine vm1 : vms) {
if (vm1.name().equals(vmName)) {
foundVM = vm1;
break;
}
}
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(regionProxPlacementGroup, foundVM.region());
foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(foundVM);
Assertions.assertEquals(regionProxPlacementGroup, foundVM.region());
Assertions.assertEquals("Windows_Server", foundVM.licenseType());
PowerState powerState = foundVM.powerState();
Assertions.assertEquals(powerState, PowerState.RUNNING);
VirtualMachineInstanceView instanceView = foundVM.instanceView();
Assertions.assertNotNull(instanceView);
Assertions.assertNotNull(instanceView.statuses().size() > 0);
Assertions.assertNotNull(foundVM.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0)));
Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds());
Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty());
Assertions
.assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0)));
VirtualMachine updatedVm = foundVM.update().withoutProximityPlacementGroup().apply();
Assertions.assertNotNull(updatedVm.proximityPlacementGroup());
Assertions.assertEquals(proxGroupType, updatedVm.proximityPlacementGroup().proximityPlacementGroupType());
Assertions.assertNotNull(updatedVm.proximityPlacementGroup().availabilitySetIds());
Assertions.assertFalse(updatedVm.proximityPlacementGroup().availabilitySetIds().isEmpty());
Assertions
.assertTrue(
setCreated.id().equalsIgnoreCase(updatedVm.proximityPlacementGroup().availabilitySetIds().get(0)));
computeManager.virtualMachines().deleteById(foundVM.id());
computeManager.availabilitySets().deleteById(setCreated.id());
}
@Test
public void canCreateVirtualMachinesAndRelatedResourcesInParallel() throws Exception {
String vmNamePrefix = "vmz";
String publicIpNamePrefix = generateRandomResourceName("pip-", 15);
String networkNamePrefix = generateRandomResourceName("vnet-", 15);
int count = 5;
CreatablesInfo creatablesInfo =
prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count);
List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables;
List<String> networkCreatableKeys = creatablesInfo.networkCreatableKeys;
List<String> publicIpCreatableKeys = creatablesInfo.publicIpCreatableKeys;
CreatedResources<VirtualMachine> createdVirtualMachines =
computeManager.virtualMachines().create(virtualMachineCreatables);
Assertions.assertTrue(createdVirtualMachines.size() == count);
Set<String> virtualMachineNames = new HashSet<>();
for (int i = 0; i < count; i++) {
virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i));
}
for (VirtualMachine virtualMachine : createdVirtualMachines.values()) {
Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name()));
Assertions.assertNotNull(virtualMachine.id());
}
Set<String> networkNames = new HashSet<>();
for (int i = 0; i < count; i++) {
networkNames.add(String.format("%s-%d", networkNamePrefix, i));
}
for (String networkCreatableKey : networkCreatableKeys) {
Network createdNetwork = (Network) createdVirtualMachines.createdRelatedResource(networkCreatableKey);
Assertions.assertNotNull(createdNetwork);
Assertions.assertTrue(networkNames.contains(createdNetwork.name()));
}
Set<String> publicIPAddressNames = new HashSet<>();
for (int i = 0; i < count; i++) {
publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i));
}
for (String publicIpCreatableKey : publicIpCreatableKeys) {
PublicIpAddress createdPublicIpAddress =
(PublicIpAddress) createdVirtualMachines.createdRelatedResource(publicIpCreatableKey);
Assertions.assertNotNull(createdPublicIpAddress);
Assertions.assertTrue(publicIPAddressNames.contains(createdPublicIpAddress.name()));
}
}
@Test
public void canStreamParallelCreatedVirtualMachinesAndRelatedResources() throws Exception {
String vmNamePrefix = "vmz";
String publicIpNamePrefix = generateRandomResourceName("pip-", 15);
String networkNamePrefix = generateRandomResourceName("vnet-", 15);
int count = 5;
final Set<String> virtualMachineNames = new HashSet<>();
for (int i = 0; i < count; i++) {
virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i));
}
final Set<String> networkNames = new HashSet<>();
for (int i = 0; i < count; i++) {
networkNames.add(String.format("%s-%d", networkNamePrefix, i));
}
final Set<String> publicIPAddressNames = new HashSet<>();
for (int i = 0; i < count; i++) {
publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i));
}
final CreatablesInfo creatablesInfo =
prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count);
final AtomicInteger resourceCount = new AtomicInteger(0);
List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables;
computeManager
.virtualMachines()
.createAsync(virtualMachineCreatables)
.map(
createdResource -> {
if (createdResource instanceof Resource) {
Resource resource = (Resource) createdResource;
System.out.println("Created: " + resource.id());
if (resource instanceof VirtualMachine) {
VirtualMachine virtualMachine = (VirtualMachine) resource;
Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name()));
Assertions.assertNotNull(virtualMachine.id());
} else if (resource instanceof Network) {
Network network = (Network) resource;
Assertions.assertTrue(networkNames.contains(network.name()));
Assertions.assertNotNull(network.id());
} else if (resource instanceof PublicIpAddress) {
PublicIpAddress publicIPAddress = (PublicIpAddress) resource;
Assertions.assertTrue(publicIPAddressNames.contains(publicIPAddress.name()));
Assertions.assertNotNull(publicIPAddress.id());
}
}
resourceCount.incrementAndGet();
return createdResource;
})
.blockLast();
networkNames.forEach(name -> {
Assertions.assertNotNull(networkManager.networks().getByResourceGroup(rgName, name));
});
publicIPAddressNames.forEach(name -> {
Assertions.assertNotNull(networkManager.publicIpAddresses().getByResourceGroup(rgName, name));
});
Assertions.assertEquals(1, storageManager.storageAccounts().listByResourceGroup(rgName).stream().count());
Assertions.assertEquals(count, networkManager.networkInterfaces().listByResourceGroup(rgName).stream().count());
Assertions.assertEquals(count, resourceCount.get());
}
@Test
public void canSetStorageAccountForUnmanagedDisk() {
final String storageName = generateRandomResourceName("st", 14);
StorageAccount storageAccount =
storageManager
.storageAccounts()
.define(storageName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withSku(StorageAccountSkuType.PREMIUM_LRS)
.create();
VirtualMachine virtualMachine =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.withUnmanagedDisks()
.defineUnmanagedDataDisk("disk1")
.withNewVhd(100)
.withLun(2)
.storeAt(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd")
.attach()
.defineUnmanagedDataDisk("disk2")
.withNewVhd(100)
.withLun(3)
.storeAt(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd")
.attach()
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4"))
.withOSDiskCaching(CachingTypes.READ_WRITE)
.create();
Map<Integer, VirtualMachineUnmanagedDataDisk> unmanagedDataDisks = virtualMachine.unmanagedDataDisks();
Assertions.assertNotNull(unmanagedDataDisks);
Assertions.assertEquals(2, unmanagedDataDisks.size());
VirtualMachineUnmanagedDataDisk firstUnmanagedDataDisk = unmanagedDataDisks.get(2);
Assertions.assertNotNull(firstUnmanagedDataDisk);
VirtualMachineUnmanagedDataDisk secondUnmanagedDataDisk = unmanagedDataDisks.get(3);
Assertions.assertNotNull(secondUnmanagedDataDisk);
String createdVhdUri1 = firstUnmanagedDataDisk.vhdUri();
String createdVhdUri2 = secondUnmanagedDataDisk.vhdUri();
Assertions.assertNotNull(createdVhdUri1);
Assertions.assertNotNull(createdVhdUri2);
computeManager.virtualMachines().deleteById(virtualMachine.id());
virtualMachine =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.withUnmanagedDisks()
.withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd")
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4"))
.create();
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
unmanagedDataDisks = virtualMachine.unmanagedDataDisks();
Assertions.assertNotNull(unmanagedDataDisks);
Assertions.assertEquals(1, unmanagedDataDisks.size());
firstUnmanagedDataDisk = null;
for (VirtualMachineUnmanagedDataDisk unmanagedDisk : unmanagedDataDisks.values()) {
firstUnmanagedDataDisk = unmanagedDisk;
break;
}
Assertions.assertNotNull(firstUnmanagedDataDisk.vhdUri());
Assertions.assertTrue(firstUnmanagedDataDisk.vhdUri().equalsIgnoreCase(createdVhdUri1));
virtualMachine
.update()
.withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd")
.apply();
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
unmanagedDataDisks = virtualMachine.unmanagedDataDisks();
Assertions.assertNotNull(unmanagedDataDisks);
Assertions.assertEquals(2, unmanagedDataDisks.size());
}
@Test
public void canUpdateTagsOnVM() {
VirtualMachine virtualMachine =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("firstuser")
.withSsh(sshPublicKey())
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.create();
virtualMachine.update().withTag("test", "testValue").apply();
Assertions.assertEquals("testValue", virtualMachine.innerModel().tags().get("test"));
Map<String, String> testTags = new HashMap<String, String>();
testTags.put("testTag", "testValue");
virtualMachine.update().withTags(testTags).apply();
Assertions.assertEquals(testTags.get("testTag"), virtualMachine.innerModel().tags().get("testTag"));
}
@Test
public void canRunScriptOnVM() {
VirtualMachine virtualMachine =
computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("firstuser")
.withSsh(sshPublicKey())
.create();
List<String> installGit = new ArrayList<>();
installGit.add("sudo apt-get update");
installGit.add("sudo apt-get install -y git");
RunCommandResult runResult =
virtualMachine.runShellScript(installGit, new ArrayList<RunCommandInputParameter>());
Assertions.assertNotNull(runResult);
Assertions.assertNotNull(runResult.value());
Assertions.assertTrue(runResult.value().size() > 0);
}
@Test
@DoNotRecord(skipInPlayback = true)
public void canPerformSimulateEvictionOnSpotVirtualMachine() {
VirtualMachine virtualMachine = computeManager.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("firstuser")
.withSsh(sshPublicKey())
.withSpotPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE)
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
.create();
Assertions.assertNotNull(virtualMachine.osDiskStorageAccountType());
Assertions.assertTrue(virtualMachine.osDiskSize() > 0);
Disk disk = computeManager.disks().getById(virtualMachine.osDiskId());
Assertions.assertNotNull(disk);
Assertions.assertEquals(DiskState.ATTACHED, disk.innerModel().diskState());
virtualMachine.simulateEviction();
boolean deallocated = false;
int pollIntervalInMinutes = 5;
for (int i = 0; i < 30; i += pollIntervalInMinutes) {
ResourceManagerUtils.sleep(Duration.ofMinutes(pollIntervalInMinutes));
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
if (virtualMachine.powerState() == PowerState.DEALLOCATED) {
deallocated = true;
break;
}
}
Assertions.assertTrue(deallocated);
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
Assertions.assertNotNull(virtualMachine);
Assertions.assertNull(virtualMachine.osDiskStorageAccountType());
Assertions.assertEquals(0, virtualMachine.osDiskSize());
disk = computeManager.disks().getById(virtualMachine.osDiskId());
Assertions.assertEquals(DiskState.RESERVED, disk.innerModel().diskState());
}
@Test
public void canForceDeleteVirtualMachine() {
computeManager.virtualMachines()
.define(vmName)
.withRegion("eastus2euap")
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.create();
VirtualMachine virtualMachine = computeManager.virtualMachines().getByResourceGroup(rgName, vmName);
Assertions.assertNotNull(virtualMachine);
Assertions.assertEquals(Region.fromName("eastus2euap"), virtualMachine.region());
String nicId = virtualMachine.primaryNetworkInterfaceId();
computeManager.virtualMachines().deleteById(virtualMachine.id(), true);
try {
virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
} catch (ManagementException ex) {
virtualMachine = null;
Assertions.assertEquals(404, ex.getResponse().getStatusCode());
}
Assertions.assertNull(virtualMachine);
NetworkInterface nic = networkManager.networkInterfaces().getById(nicId);
Assertions.assertNotNull(nic);
}
@Test
public void canCreateVirtualMachineWithDeleteOption() throws Exception {
Region region = Region.US_WEST2;
final String publicIpDnsLabel = generateRandomResourceName("pip", 20);
Network network = this
.networkManager
.networks()
.define("network1")
.withRegion(region)
.withNewResourceGroup(rgName)
.withAddressSpace("10.0.0.0/24")
.withSubnet("default", "10.0.0.0/24")
.create();
VirtualMachine vm1 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withNewPrimaryPublicIPAddress(publicIpDnsLabel/*, DeleteOptions.DELETE*/)
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withNewDataDisk(10)
.withNewDataDisk(computeManager.disks()
.define("datadisk2")
.withRegion(region)
.withExistingResourceGroup(rgName)
.withData()
.withSizeInGB(10))
.withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE)
.withOSDiskDeleteOptions(DeleteOptions.DELETE)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
Assertions.assertEquals(DeleteOptions.DELETE, vm1.osDiskDeleteOptions());
Assertions.assertEquals(DeleteOptions.DELETE, vm1.dataDisks().get(0).deleteOptions());
Assertions.assertEquals(DeleteOptions.DELETE, vm1.dataDisks().get(1).deleteOptions());
Assertions.assertEquals(vm1.id(), computeManager.virtualMachines().getById(vm1.id()).id());
computeManager.virtualMachines().deleteById(vm1.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(2, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count());
PublicIpAddress publicIpAddress = computeManager.networkManager().publicIpAddresses().listByResourceGroup(rgName).stream().findFirst().get();
computeManager.networkManager().publicIpAddresses().deleteById(publicIpAddress.id());
String secondaryNicName = generateRandomResourceName("nic", 10);
Creatable<NetworkInterface> secondaryNetworkInterfaceCreatable =
this
.networkManager
.networkInterfaces()
.define(secondaryNicName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic();
VirtualMachine vm2 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withOSDiskDeleteOptions(DeleteOptions.DELETE)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable, DeleteOptions.DELETE)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
computeManager.virtualMachines().deleteById(vm2.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(1, computeManager.resourceManager().genericResources().listByResourceGroup(rgName).stream().count());
secondaryNetworkInterfaceCreatable =
this
.networkManager
.networkInterfaces()
.define(secondaryNicName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic();
VirtualMachine vm3 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withNewDataDisk(10)
.withNewDataDisk(computeManager.disks()
.define("datadisk2")
.withRegion(region)
.withExistingResourceGroup(rgName)
.withData()
.withSizeInGB(10))
.withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
Assertions.assertEquals(DeleteOptions.DETACH, vm3.osDiskDeleteOptions());
Assertions.assertEquals(DeleteOptions.DETACH, vm3.dataDisks().get(0).deleteOptions());
Assertions.assertEquals(DeleteOptions.DETACH, vm3.dataDisks().get(1).deleteOptions());
computeManager.virtualMachines().deleteById(vm3.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(3, computeManager.disks().listByResourceGroup(rgName).stream().count());
Assertions.assertEquals(2, computeManager.networkManager().networkInterfaces().listByResourceGroup(rgName).stream().count());
}
@Test
public void canUpdateVirtualMachineWithDeleteOption() throws Exception {
Region region = Region.US_WEST2;
Network network = this
.networkManager
.networks()
.define("network1")
.withRegion(region)
.withNewResourceGroup(rgName)
.withAddressSpace("10.0.0.0/24")
.withSubnet("default", "10.0.0.0/24")
.create();
VirtualMachine vm1 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withNewDataDisk(10)
.withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE)
.withOSDiskDeleteOptions(DeleteOptions.DELETE)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
vm1.update()
.withNewDataDisk(10)
.apply();
computeManager.virtualMachines().deleteById(vm1.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(1, computeManager.disks().listByResourceGroup(rgName).stream().count());
Disk disk = computeManager.disks().listByResourceGroup(rgName).stream().findFirst().get();
computeManager.disks().deleteById(disk.id());
VirtualMachine vm2 = computeManager
.virtualMachines()
.define(vmName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet("default")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testuser")
.withSsh(sshPublicKey())
.withNewDataDisk(10)
.withPrimaryNetworkInterfaceDeleteOptions(DeleteOptions.DELETE)
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
vm2.update()
.withNewDataDisk(10)
.withDataDiskDefaultDeleteOptions(DeleteOptions.DELETE)
.apply();
computeManager.virtualMachines().deleteById(vm2.id());
ResourceManagerUtils.sleep(Duration.ofSeconds(10));
Assertions.assertEquals(2, computeManager.disks().listByResourceGroup(rgName).stream().count());
}
@Test
public void canHibernateVirtualMachine() {
VirtualMachine vm = computeManager.virtualMachines()
.define(vmName)
.withRegion("eastus2euap")
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER)
.withAdminUsername("Foo12")
.withAdminPassword(password())
.withSize(VirtualMachineSizeTypes.STANDARD_D2S_V3)
.enableHibernation()
.create();
Assertions.assertTrue(vm.isHibernationEnabled());
vm.deallocate(true);
InstanceViewStatus hibernationStatus = vm.instanceView().statuses().stream()
.filter(status -> "HibernationState/Hibernated".equals(status.code()))
.findFirst().orElse(null);
Assertions.assertNotNull(hibernationStatus);
vm.start();
vm.deallocate();
vm.update()
.disableHibernation()
.apply();
Assertions.assertFalse(vm.isHibernationEnabled());
}
@Test
public void canOperateVirtualMachine() {
VirtualMachine vm = computeManager.virtualMachines()
.define(vmName)
.withRegion(Region.US_WEST3)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("Foo12")
.withSsh(sshPublicKey())
.withSize(VirtualMachineSizeTypes.STANDARD_A1_V2)
.create();
Assertions.assertEquals(PowerState.RUNNING, vm.powerState());
vm.redeploy();
vm.powerOff(true);
vm.refreshInstanceView();
Assertions.assertEquals(PowerState.STOPPED, vm.powerState());
vm.start();
vm.refreshInstanceView();
Assertions.assertEquals(PowerState.RUNNING, vm.powerState());
vm.restart();
vm.refreshInstanceView();
Assertions.assertEquals(PowerState.RUNNING, vm.powerState());
vm.deallocate();
vm.refreshInstanceView();
Assertions.assertEquals(PowerState.DEALLOCATED, vm.powerState());
}
@Test
private CreatablesInfo prepareCreatableVirtualMachines(
Region region, String vmNamePrefix, String networkNamePrefix, String publicIpNamePrefix, int vmCount) {
Creatable<ResourceGroup> resourceGroupCreatable =
resourceManager.resourceGroups().define(rgName).withRegion(region);
Creatable<StorageAccount> storageAccountCreatable =
storageManager
.storageAccounts()
.define(generateRandomResourceName("stg", 20))
.withRegion(region)
.withNewResourceGroup(resourceGroupCreatable);
List<String> networkCreatableKeys = new ArrayList<>();
List<String> publicIpCreatableKeys = new ArrayList<>();
List<Creatable<VirtualMachine>> virtualMachineCreatables = new ArrayList<>();
for (int i = 0; i < vmCount; i++) {
Creatable<Network> networkCreatable =
networkManager
.networks()
.define(String.format("%s-%d", networkNamePrefix, i))
.withRegion(region)
.withNewResourceGroup(resourceGroupCreatable)
.withAddressSpace("10.0.0.0/28");
networkCreatableKeys.add(networkCreatable.key());
Creatable<PublicIpAddress> publicIPAddressCreatable =
networkManager
.publicIpAddresses()
.define(String.format("%s-%d", publicIpNamePrefix, i))
.withRegion(region)
.withNewResourceGroup(resourceGroupCreatable);
publicIpCreatableKeys.add(publicIPAddressCreatable.key());
Creatable<VirtualMachine> virtualMachineCreatable =
computeManager
.virtualMachines()
.define(String.format("%s-%d", vmNamePrefix, i))
.withRegion(region)
.withNewResourceGroup(resourceGroupCreatable)
.withNewPrimaryNetwork(networkCreatable)
.withPrimaryPrivateIPAddressDynamic()
.withNewPrimaryPublicIPAddress(publicIPAddressCreatable)
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("tirekicker")
.withSsh(sshPublicKey())
.withUnmanagedDisks()
.withNewStorageAccount(storageAccountCreatable);
virtualMachineCreatables.add(virtualMachineCreatable);
}
CreatablesInfo creatablesInfo = new CreatablesInfo();
creatablesInfo.virtualMachineCreatables = virtualMachineCreatables;
creatablesInfo.networkCreatableKeys = networkCreatableKeys;
creatablesInfo.publicIpCreatableKeys = publicIpCreatableKeys;
return creatablesInfo;
}
class CreatablesInfo {
private List<Creatable<VirtualMachine>> virtualMachineCreatables;
List<String> networkCreatableKeys;
List<String> publicIpCreatableKeys;
}
} |
I think you can return dataLakeFileAsyncClient.createIfNotExistsWithResponse instead and then you don't have to duplicate the logic of checking again. | public Mono<Response<DataLakeFileAsyncClient>> createFileIfNotExistsWithResponse(String fileName, String permissions, String umask, PathHttpHeaders headers, Map<String, String> metadata, Context context) {
DataLakeRequestConditions requestConditions = new DataLakeRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
DataLakeFileAsyncClient dataLakeFileAsyncClient = getFileAsyncClient(fileName);
return dataLakeFileAsyncClient.createWithResponse(permissions, umask, pathResourceType,
headers, metadata, requestConditions, context).onErrorResume(t -> t instanceof DataLakeStorageException && ((DataLakeStorageException) t).getStatusCode() == 409, t -> Mono.empty())
.map(response -> new SimpleResponse<>(response, dataLakeFileAsyncClient));
} | return dataLakeFileAsyncClient.createWithResponse(permissions, umask, pathResourceType, | new DataLakeRequestConditions();
if (!overwrite) {
requestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
} | class DataLakeDirectoryAsyncClient extends DataLakePathAsyncClient {
private final ClientLogger logger = new ClientLogger(DataLakeDirectoryAsyncClient.class);
/**
* Package-private constructor for use by {@link DataLakePathClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param fileSystemName The file system name.
* @param directoryName The directory name.
* @param blockBlobAsyncClient The underlying {@link BlobContainerAsyncClient}
*/
DataLakeDirectoryAsyncClient(HttpPipeline pipeline, String url, DataLakeServiceVersion serviceVersion,
String accountName, String fileSystemName, String directoryName, BlockBlobAsyncClient blockBlobAsyncClient) {
super(pipeline, url, serviceVersion, accountName, fileSystemName, directoryName, PathResourceType.DIRECTORY,
blockBlobAsyncClient);
}
DataLakeDirectoryAsyncClient(DataLakePathAsyncClient dataLakePathAsyncClient) {
super(dataLakePathAsyncClient.getHttpPipeline(), dataLakePathAsyncClient.getAccountUrl(),
dataLakePathAsyncClient.getServiceVersion(), dataLakePathAsyncClient.getAccountName(),
dataLakePathAsyncClient.getFileSystemName(), Utility.urlEncode(dataLakePathAsyncClient.pathName),
PathResourceType.DIRECTORY, dataLakePathAsyncClient.getBlockBlobAsyncClient());
}
/**
* Gets the URL of the directory represented by this client on the Data Lake service.
*
* @return the URL.
*/
public String getDirectoryUrl() {
return getPathUrl();
}
/**
* Gets the path of this directory, not including the name of the resource itself.
*
* @return The path of the directory.
*/
public String getDirectoryPath() {
return getObjectPath();
}
/**
* Gets the name of this directory, not including its full path.
*
* @return The name of the directory.
*/
public String getDirectoryName() {
return getObjectName();
}
/**
* Deletes a directory.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.delete -->
* <pre>
* client.delete&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.delete -->
*
* <p>For more information see the
* <a href="https:
* Docs</a></p>
*
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> delete() {
try {
return deleteWithResponse(false, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a directory.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* boolean recursive = false; &
*
* client.deleteWithResponse&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteWithResponse
*
* <p>For more information see the
* <a href="https:
* Docs</a></p>
*
* @param recursive Whether or not to delete all paths beneath the directory.
* @param requestConditions {@link DataLakeRequestConditions}
*
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteWithResponse(boolean recursive, DataLakeRequestConditions requestConditions) {
try {
return withContext(context -> deleteWithResponse(recursive, requestConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new DataLakeFileAsyncClient object by concatenating fileName to the end of
* DataLakeDirectoryAsyncClient's URL. The new DataLakeFileAsyncClient uses the same request policy pipeline as the
* DataLakeDirectoryAsyncClient.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.getFileAsyncClient
* <pre>
* DataLakeFileAsyncClient dataLakeFileClient = client.getFileAsyncClient&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.getFileAsyncClient
*
* @param fileName A {@code String} representing the name of the file.
* @return A new {@link DataLakeFileAsyncClient} object which references the file with the specified name in this
* file system.
*/
public DataLakeFileAsyncClient getFileAsyncClient(String fileName) {
Objects.requireNonNull(fileName, "'fileName' can not be set to null");
BlockBlobAsyncClient blockBlobAsyncClient = prepareBuilderAppendPath(fileName).buildBlockBlobAsyncClient();
String pathPrefix = getObjectPath().isEmpty() ? "" : getObjectPath() + "/";
return new DataLakeFileAsyncClient(getHttpPipeline(), getAccountUrl(),
getServiceVersion(), getAccountName(), getFileSystemName(), Utility.urlEncode(pathPrefix
+ Utility.urlDecode(fileName)), blockBlobAsyncClient);
}
/**
* Creates a new file within a directory. By default this method will not overwrite an existing file.
* For more information, see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFile
* <pre>
* DataLakeFileAsyncClient fileClient = client.createFile&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFile
*
* @param fileName Name of the file to create.
* @return A {@link Mono} containing a {@link DataLakeFileAsyncClient} used to interact with the file created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileAsyncClient> createFile(String fileName) {
return createFile(fileName, false);
}
/**
* Creates a new file within a directory. For more information, see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFile
* <pre>
* boolean overwrite = false; &
* DataLakeFileAsyncClient fClient = client.createFile&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFile
*
* @param fileName Name of the file to create.
* @param overwrite Whether or not to overwrite, should the file exist.
* @return A {@link Mono} containing a {@link DataLakeFileAsyncClient} used to interact with the file created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileAsyncClient> createFile(String fileName, boolean overwrite) {
DataLakeRequestConditions requestConditions =
try {
return createFileWithResponse(fileName, null, null, null, null, requestConditions)
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new file within a directory. If a file with the same name already exists, the file will be
* overwritten. For more information, see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFileWithResponse
* <pre>
* PathHttpHeaders httpHeaders = new PathHttpHeaders&
* .setContentLanguage&
* .setContentType&
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* String permissions = "permissions";
* String umask = "umask";
* DataLakeFileAsyncClient newFileClient = client.createFileWithResponse&
* permissions, umask, httpHeaders, Collections.singletonMap&
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFileWithResponse
*
* @param fileName Name of the file to create.
* @param permissions POSIX access permissions for the file owner, the file owning group, and others.
* @param umask Restricts permissions of the file to be created.
* @param headers {@link PathHttpHeaders}
* @param metadata Metadata to associate with the file. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeFileAsyncClient} used to interact with the file created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileAsyncClient>> createFileWithResponse(String fileName, String permissions,
String umask, PathHttpHeaders headers, Map<String, String> metadata,
DataLakeRequestConditions requestConditions) {
try {
DataLakeFileAsyncClient dataLakeFileAsyncClient = getFileAsyncClient(fileName);
return dataLakeFileAsyncClient.createWithResponse(permissions, umask, headers, metadata, requestConditions)
.map(response -> new SimpleResponse<>(response, dataLakeFileAsyncClient));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileAsyncClient> createFileIfNotExists(String fileName) {
return createFileIfNotExistsWithResponse(fileName, null, null, null, null).flatMap(FluxUtil::toMono);
}
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileAsyncClient>> createFileIfNotExistsWithResponse(String fileName, String permissions,
String umask, PathHttpHeaders headers, Map<String, String> metadata) {
return createFileIfNotExistsWithResponse(fileName, permissions, umask, headers, metadata, null);
}
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileAsyncClient>> createFileIfNotExistsWithResponse(String fileName, String permissions, String umask, PathHttpHeaders headers, Map<String, String> metadata, Context context) {
DataLakeRequestConditions requestConditions = new DataLakeRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
DataLakeFileAsyncClient dataLakeFileAsyncClient = getFileAsyncClient(fileName);
return dataLakeFileAsyncClient.createWithResponse(permissions, umask, pathResourceType,
headers, metadata, requestConditions, context).onErrorResume(t -> t instanceof DataLakeStorageException && ((DataLakeStorageException) t).getStatusCode() == 409, t -> Mono.empty())
.map(response -> new SimpleResponse<>(response, dataLakeFileAsyncClient));
}
/*
Mono<Response<AppendBlobItem>> createIfNotExistsWithResponse(AppendBlobCreateOptions options, Context context) {
options.setRequestConditions(new AppendBlobRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD));
return createWithResponse(options, context).onErrorResume(t -> t instanceof BlobStorageException && ((BlobStorageException) t).getStatusCode() == 409,
t -> Mono.empty());
}
.onErrorResume(t -> instanceof DataLakeStorageException && ((DataLakeStorageException) t).getStatusCode() == 409,
*/
/**
* Deletes the specified file in the file system. If the file doesn't exist the operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFile
* <pre>
* client.deleteFile&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFile
*
* @param fileName Name of the file to delete.
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteFile(String fileName) {
try {
return deleteFileWithResponse(fileName, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified file in the directory. If the file doesn't exist the operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFileWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
*
* client.deleteFileWithResponse&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFileWithResponse
*
* @param fileName Name of the file to delete.
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteFileWithResponse(String fileName, DataLakeRequestConditions requestConditions) {
try {
return getFileAsyncClient(fileName).deleteWithResponse(requestConditions);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteFileIfExists(String fileName) {
try {
return deleteFileIfExistsWithResponse(fileName, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteFileIfExistsWithResponse(String fileName, DataLakeRequestConditions requestConditions) {
return deleteFileIfExistsWithResponse(fileName, requestConditions, null);
}
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteFileIfExistsWithResponse(String fileName, DataLakeRequestConditions requestConditions, Context context) {
return getFileAsyncClient(fileName).deleteWithResponse(null, requestConditions, context)
.onErrorResume(t -> t instanceof DataLakeStorageException && ((DataLakeStorageException)t).getStatusCode() == 404,
t -> Mono.empty());
}
/**
* Creates a new DataLakeDirectoryAsyncClient object by concatenating subdirectoryName to the end of
* DataLakeDirectoryAsyncClient's URL. The new DataLakeDirectoryAsyncClient uses the same request policy pipeline
* as the DataLakeDirectoryAsyncClient.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.getSubdirectoryAsyncClient
* <pre>
* DataLakeDirectoryAsyncClient dataLakeDirectoryClient = client.getSubdirectoryAsyncClient&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.getSubdirectoryAsyncClient
*
* @param subdirectoryName A {@code String} representing the name of the sub-directory.
* @return A new {@link DataLakeDirectoryAsyncClient} object which references the directory with the specified name
* in this file system.
*/
public DataLakeDirectoryAsyncClient getSubdirectoryAsyncClient(String subdirectoryName) {
Objects.requireNonNull(subdirectoryName, "'subdirectoryName' can not be set to null");
BlockBlobAsyncClient blockBlobAsyncClient = prepareBuilderAppendPath(subdirectoryName)
.buildBlockBlobAsyncClient();
String pathPrefix = getObjectPath().isEmpty() ? "" : getObjectPath() + "/";
return new DataLakeDirectoryAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(),
getAccountName(), getFileSystemName(),
Utility.urlEncode(pathPrefix + Utility.urlDecode(subdirectoryName)), blockBlobAsyncClient);
}
/**
* Creates a new sub-directory within a directory. By default this method will not overwrite an existing
* sub-directory. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectory
* <pre>
* DataLakeDirectoryAsyncClient directoryClient = client.createSubdirectory&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectory
*
* @param subdirectoryName Name of the sub-directory to create.
* @return A {@link Mono} containing a {@link DataLakeDirectoryAsyncClient} used to interact with the directory
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeDirectoryAsyncClient> createSubdirectory(String subdirectoryName) {
return createSubdirectory(subdirectoryName, false);
}
/**
* Creates a new sub-directory within a directory. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectory
* <pre>
* boolean overwrite = false; &
* DataLakeDirectoryAsyncClient dClient = client.createSubdirectory&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectory
*
* @param subdirectoryName Name of the sub-directory to create.
* @param overwrite Whether or not to overwrite, should the sub directory exist.
* @return A {@link Mono} containing a {@link DataLakeDirectoryAsyncClient} used to interact with the directory
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeDirectoryAsyncClient> createSubdirectory(String subdirectoryName, boolean overwrite) {
DataLakeRequestConditions requestConditions = new DataLakeRequestConditions();
if (!overwrite) {
requestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
try {
return createSubdirectoryWithResponse(subdirectoryName, null, null, null, null, requestConditions)
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new sub-directory within a directory. If a sub-directory with the same name already exists, the
* sub-directory will be overwritten. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectoryWithResponse
* <pre>
* PathHttpHeaders httpHeaders = new PathHttpHeaders&
* .setContentLanguage&
* .setContentType&
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* String permissions = "permissions";
* String umask = "umask";
* DataLakeDirectoryAsyncClient newDirectoryClient = client.createSubdirectoryWithResponse&
* directoryName, permissions, umask, httpHeaders, Collections.singletonMap&
* requestConditions
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectoryWithResponse
*
* @param subdirectoryName Name of the sub-directory to create.
* @param permissions POSIX access permissions for the sub-directory owner, the sub-directory owning group, and
* others.
* @param umask Restricts permissions of the sub-directory to be created.
* @param headers {@link PathHttpHeaders}
* @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeDirectoryAsyncClient} used to interact with the sub-directory created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeDirectoryAsyncClient>> createSubdirectoryWithResponse(String subdirectoryName,
String permissions, String umask, PathHttpHeaders headers, Map<String, String> metadata,
DataLakeRequestConditions requestConditions) {
try {
DataLakeDirectoryAsyncClient dataLakeDirectoryAsyncClient = getSubdirectoryAsyncClient(subdirectoryName);
return dataLakeDirectoryAsyncClient.createWithResponse(permissions, umask, headers, metadata,
requestConditions).map(response -> new SimpleResponse<>(response, dataLakeDirectoryAsyncClient));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified sub-directory in the directory. If the sub-directory doesn't exist or is not empty the
* operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectory
* <pre>
* client.deleteSubdirectory&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectory
*
* @param subdirectoryName Name of the sub-directory to delete.
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteSubdirectory(String subdirectoryName) {
try {
return deleteSubdirectoryWithResponse(subdirectoryName, false, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified sub-directory in the directory. If the sub-directory doesn't exist or is not empty the
* operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectoryWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* boolean recursive = false; &
*
* client.deleteSubdirectoryWithResponse&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectoryWithResponse
*
* @param directoryName Name of the sub-directory to delete.
* @param recursive Whether or not to delete all paths beneath the sub-directory.
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubdirectoryWithResponse(String directoryName, boolean recursive,
DataLakeRequestConditions requestConditions) {
try {
return getSubdirectoryAsyncClient(directoryName).deleteWithResponse(recursive, requestConditions);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Moves the directory to another location within the file system.
* For more information see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.rename
* <pre>
* DataLakeDirectoryAsyncClient renamedClient = client.rename&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.rename
*
* @param destinationFileSystem The file system of the destination within the account.
* {@code null} for the current file system.
* @param destinationPath Relative path from the file system to rename the directory to, excludes the file system
* name. For example if you want to move a directory with fileSystem = "myfilesystem", path = "mydir/mysubdir" to
* another path in myfilesystem (ex: newdir) then set the destinationPath = "newdir"
* @return A {@link Mono} containing a {@link DataLakeDirectoryAsyncClient} used to interact with the new directory
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeDirectoryAsyncClient> rename(String destinationFileSystem, String destinationPath) {
try {
return renameWithResponse(destinationFileSystem, destinationPath, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Moves the directory to another location within the file system.
* For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.renameWithResponse
* <pre>
* DataLakeRequestConditions sourceRequestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* DataLakeRequestConditions destinationRequestConditions = new DataLakeRequestConditions&
*
* DataLakeDirectoryAsyncClient newRenamedClient = client.renameWithResponse&
* sourceRequestConditions, destinationRequestConditions&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.renameWithResponse
*
* @param destinationFileSystem The file system of the destination within the account.
* {@code null} for the current file system.
* @param destinationPath Relative path from the file system to rename the directory to, excludes the file system
* name. For example if you want to move a directory with fileSystem = "myfilesystem", path = "mydir/mysubdir" to
* another path in myfilesystem (ex: newdir) then set the destinationPath = "newdir"
* @param sourceRequestConditions {@link DataLakeRequestConditions} against the source.
* @param destinationRequestConditions {@link DataLakeRequestConditions} against the destination.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeDirectoryAsyncClient} used to interact with the directory created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeDirectoryAsyncClient>> renameWithResponse(String destinationFileSystem,
String destinationPath, DataLakeRequestConditions sourceRequestConditions,
DataLakeRequestConditions destinationRequestConditions) {
try {
return withContext(context -> renameWithResponse(destinationFileSystem, destinationPath,
sourceRequestConditions, destinationRequestConditions, context)).map(
response -> new SimpleResponse<>(response, new DataLakeDirectoryAsyncClient(response.getValue())));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Returns a reactive Publisher emitting all the files/directories in this directory lazily as needed. For more
* information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.listPaths -->
* <pre>
* client.listPaths&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.listPaths -->
*
* @return A reactive response emitting the list of files/directories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<PathItem> listPaths() {
return this.listPaths(false, false, null);
}
/**
* Returns a reactive Publisher emitting all the files/directories in this directory lazily as needed. For more
* information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.listPaths
* <pre>
* client.listPaths&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.listPaths
*
* @param recursive Specifies if the call should recursively include all paths.
* @param userPrincipleNameReturned If "true", the user identity values returned in the x-ms-owner, x-ms-group,
* and x-ms-acl response headers will be transformed from Azure Active Directory Object IDs to User Principal Names.
* If "false", the values will be returned as Azure Active Directory Object IDs.
* The default value is false. Note that group and application Object IDs are not translated because they do not
* have unique friendly names.
* @param maxResults Specifies the maximum number of blobs to return per page, including all BlobPrefix elements. If
* the request does not specify maxResults or specifies a value greater than 5,000, the server will return up to
* 5,000 items per page.
* @return A reactive response emitting the list of files/directories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<PathItem> listPaths(boolean recursive, boolean userPrincipleNameReturned, Integer maxResults) {
try {
return listPathsWithOptionalTimeout(recursive, userPrincipleNameReturned, maxResults, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<PathItem> listPathsWithOptionalTimeout(boolean recursive, boolean userPrincipleNameReturned,
Integer maxResults, Duration timeout) {
BiFunction<String, Integer, Mono<PagedResponse<PathItem>>> func =
(marker, pageSize) -> listPathsSegment(marker, recursive, userPrincipleNameReturned,
pageSize == null ? maxResults : pageSize, timeout)
.map(response -> {
List<PathItem> value = response.getValue() == null
? Collections.emptyList()
: response.getValue().getPaths().stream()
.map(Transforms::toPathItem)
.collect(Collectors.toList());
return new PagedResponseBase<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
value,
response.getDeserializedHeaders().getXMsContinuation(),
response.getDeserializedHeaders());
});
return new PagedFlux<>(pageSize -> func.apply(null, pageSize), func);
}
private Mono<FileSystemsListPathsResponse> listPathsSegment(String marker, boolean recursive,
boolean userPrincipleNameReturned, Integer maxResults, Duration timeout) {
return StorageImplUtils.applyOptionalTimeout(
this.fileSystemDataLakeStorage.getFileSystems().listPathsWithResponseAsync(
recursive, null, null, marker, getDirectoryPath(), maxResults, userPrincipleNameReturned,
Context.NONE), timeout);
}
/**
* Prepares a SpecializedBlobClientBuilder with the pathname appended to the end of the current BlockBlobClient's
* url
* @param pathName The name of the path to append
* @return {@link SpecializedBlobClientBuilder}
*/
SpecializedBlobClientBuilder prepareBuilderAppendPath(String pathName) {
String blobUrl = DataLakeImplUtils.endpointToDesiredEndpoint(getPathUrl(), "blob", "dfs");
return new SpecializedBlobClientBuilder()
.pipeline(getHttpPipeline())
.serviceVersion(TransformUtils.toBlobServiceVersion(getServiceVersion()))
.endpoint(StorageImplUtils.appendToUrlPath(blobUrl, pathName).toString());
}
} | class DataLakeDirectoryAsyncClient extends DataLakePathAsyncClient {
private static final ClientLogger LOGGER = new ClientLogger(DataLakeDirectoryAsyncClient.class);
/**
* Package-private constructor for use by {@link DataLakePathClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param fileSystemName The file system name.
* @param directoryName The directory name.
* @param blockBlobAsyncClient The underlying {@link BlobContainerAsyncClient}
*/
DataLakeDirectoryAsyncClient(HttpPipeline pipeline, String url, DataLakeServiceVersion serviceVersion,
String accountName, String fileSystemName, String directoryName, BlockBlobAsyncClient blockBlobAsyncClient,
AzureSasCredential sasToken) {
super(pipeline, url, serviceVersion, accountName, fileSystemName, directoryName, PathResourceType.DIRECTORY,
blockBlobAsyncClient, sasToken);
}
DataLakeDirectoryAsyncClient(DataLakePathAsyncClient dataLakePathAsyncClient) {
super(dataLakePathAsyncClient.getHttpPipeline(), dataLakePathAsyncClient.getAccountUrl(),
dataLakePathAsyncClient.getServiceVersion(), dataLakePathAsyncClient.getAccountName(),
dataLakePathAsyncClient.getFileSystemName(), Utility.urlEncode(dataLakePathAsyncClient.pathName),
PathResourceType.DIRECTORY, dataLakePathAsyncClient.getBlockBlobAsyncClient(),
dataLakePathAsyncClient.getSasToken());
}
/**
* Gets the URL of the directory represented by this client on the Data Lake service.
*
* @return the URL.
*/
public String getDirectoryUrl() {
return getPathUrl();
}
/**
* Gets the path of this directory, not including the name of the resource itself.
*
* @return The path of the directory.
*/
public String getDirectoryPath() {
return getObjectPath();
}
/**
* Gets the name of this directory, not including its full path.
*
* @return The name of the directory.
*/
public String getDirectoryName() {
return getObjectName();
}
/**
* Deletes a directory.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.delete -->
* <pre>
* client.delete&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.delete -->
*
* <p>For more information see the
* <a href="https:
* Docs</a></p>
*
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> delete() {
return deleteWithResponse(false, null).flatMap(FluxUtil::toMono);
}
/**
* Deletes a directory.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* boolean recursive = false; &
*
* client.deleteWithResponse&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteWithResponse
*
* <p>For more information see the
* <a href="https:
* Docs</a></p>
*
* @param recursive Whether to delete all paths beneath the directory.
* @param requestConditions {@link DataLakeRequestConditions}
*
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteWithResponse(boolean recursive, DataLakeRequestConditions requestConditions) {
try {
return withContext(context -> deleteWithResponse(recursive, requestConditions, context));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Deletes a directory if it exists.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteIfExists -->
* <pre>
* client.deleteIfExists&
* if &
* System.out.println&
* &
* System.out.println&
* &
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteIfExists -->
*
* <p>For more information see the
* <a href="https:
* Docs</a></p>
*
* @return a reactive response signaling completion. {@code true} indicates that the directory was successfully
* deleted, {@code true} indicates that the directory did not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> deleteIfExists() {
return deleteIfExistsWithResponse(new DataLakePathDeleteOptions())
.map(response -> response.getStatusCode() != 404);
}
/**
* Deletes a directory if it exists.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteIfExistsWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* boolean recursive = false; &
* DataLakePathDeleteOptions options = new DataLakePathDeleteOptions&
* .setRequestConditions&
*
* client.deleteIfExistsWithResponse&
* if &
* System.out.println&
* &
* System.out.println&
* &
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteIfExistsWithResponse
*
* <p>For more information see the
* <a href="https:
* Docs</a></p>
*
* @param options {@link DataLakePathDeleteOptions}
*
* @return A reactive response signaling completion. If {@link Response}'s status code is 200, the directory was
* successfully deleted. If status code is 404, the directory does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteIfExistsWithResponse(DataLakePathDeleteOptions options) {
try {
options = options == null ? new DataLakePathDeleteOptions() : options;
return deleteWithResponse(options.getIsRecursive(), options.getRequestConditions()).onErrorResume(t -> t
instanceof DataLakeStorageException && ((DataLakeStorageException) t).getStatusCode() == 404,
t -> {
HttpResponse response = ((DataLakeStorageException) t).getResponse();
return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
});
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Creates a new DataLakeFileAsyncClient object by concatenating fileName to the end of
* DataLakeDirectoryAsyncClient's URL. The new DataLakeFileAsyncClient uses the same request policy pipeline as the
* DataLakeDirectoryAsyncClient.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.getFileAsyncClient
* <pre>
* DataLakeFileAsyncClient dataLakeFileClient = client.getFileAsyncClient&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.getFileAsyncClient
*
* @param fileName A {@code String} representing the name of the file.
* @return A new {@link DataLakeFileAsyncClient} object which references the file with the specified name in this
* file system.
*/
public DataLakeFileAsyncClient getFileAsyncClient(String fileName) {
Objects.requireNonNull(fileName, "'fileName' can not be set to null");
BlockBlobAsyncClient blockBlobAsyncClient = prepareBuilderAppendPath(fileName).buildBlockBlobAsyncClient();
String pathPrefix = getObjectPath().isEmpty() ? "" : getObjectPath() + "/";
return new DataLakeFileAsyncClient(getHttpPipeline(), getAccountUrl(),
getServiceVersion(), getAccountName(), getFileSystemName(), Utility.urlEncode(pathPrefix
+ Utility.urlDecode(fileName)), blockBlobAsyncClient, this.getSasToken());
}
/**
* Creates a new file within a directory. By default, this method will not overwrite an existing file.
* For more information, see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFile
* <pre>
* DataLakeFileAsyncClient fileClient = client.createFile&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFile
*
* @param fileName Name of the file to create.
* @return A {@link Mono} containing a {@link DataLakeFileAsyncClient} used to interact with the file created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileAsyncClient> createFile(String fileName) {
return createFile(fileName, false);
}
/**
* Creates a new file within a directory. For more information, see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFile
* <pre>
* boolean overwrite = false; &
* DataLakeFileAsyncClient fClient = client.createFile&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFile
*
* @param fileName Name of the file to create.
* @param overwrite Whether to overwrite, should the file exist.
* @return A {@link Mono} containing a {@link DataLakeFileAsyncClient} used to interact with the file created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileAsyncClient> createFile(String fileName, boolean overwrite) {
DataLakeRequestConditions requestConditions =
return createFileWithResponse(fileName, null, null, null, null, requestConditions).flatMap(FluxUtil::toMono);
}
/**
* Creates a new file within a directory. If a file with the same name already exists, the file will be
* overwritten. For more information, see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFileWithResponse
* <pre>
* PathHttpHeaders httpHeaders = new PathHttpHeaders&
* .setContentLanguage&
* .setContentType&
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* String permissions = "permissions";
* String umask = "umask";
* DataLakeFileAsyncClient newFileClient = client.createFileWithResponse&
* permissions, umask, httpHeaders, Collections.singletonMap&
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFileWithResponse
*
* @param fileName Name of the file to create.
* @param permissions POSIX access permissions for the file owner, the file owning group, and others.
* @param umask Restricts permissions of the file to be created.
* @param headers {@link PathHttpHeaders}
* @param metadata Metadata to associate with the file. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeFileAsyncClient} used to interact with the file created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileAsyncClient>> createFileWithResponse(String fileName, String permissions,
String umask, PathHttpHeaders headers, Map<String, String> metadata,
DataLakeRequestConditions requestConditions) {
DataLakeFileAsyncClient dataLakeFileAsyncClient;
try {
dataLakeFileAsyncClient = getFileAsyncClient(fileName);
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
return dataLakeFileAsyncClient.createWithResponse(permissions, umask, headers, metadata, requestConditions)
.map(response -> new SimpleResponse<>(response, dataLakeFileAsyncClient));
}
/**
* Creates a new file within a directory if it does not exist. By default this method will not overwrite an existing
* file. For more information, see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFileIfNotExists
* <pre>
* DataLakeFileAsyncClient fileClient = client.createFileIfNotExists&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFileIfNotExists
*
* @param fileName Name of the file to create.
* @return A {@link Mono} containing a {@link DataLakeFileAsyncClient} used to interact with the file created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileAsyncClient> createFileIfNotExists(String fileName) {
return createFileIfNotExistsWithResponse(fileName, new DataLakePathCreateOptions()).flatMap(FluxUtil::toMono);
}
/**
* Creates a new file within a directory if it does not exist. For more information, see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFileIfNotExistsWithResponse
* <pre>
* PathHttpHeaders headers = new PathHttpHeaders&
* .setContentLanguage&
* .setContentType&
* String permissions = "permissions";
* String umask = "umask";
* DataLakePathCreateOptions options = new DataLakePathCreateOptions&
* .setPermissions&
*
* client.createFileIfNotExistsWithResponse&
* if &
* System.out.println&
* &
* System.out.println&
* &
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFileIfNotExistsWithResponse
*
* @param fileName Name of the file to create.
* @param options {@link DataLakePathCreateOptions}
* metadata key or value, it must be removed or encoded.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link DataLakeFileAsyncClient} used to interact with the file created. If {@link Response}'s status code is 201,
* a new file was successfully created. If status code is 409, a file with the same name already existed
* at this location.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileAsyncClient>> createFileIfNotExistsWithResponse(String fileName,
DataLakePathCreateOptions options) {
DataLakeFileAsyncClient dataLakeFileAsyncClient = getFileAsyncClient(fileName);
try {
return dataLakeFileAsyncClient.createIfNotExistsWithResponse(options)
.map(response -> new SimpleResponse<>(response, dataLakeFileAsyncClient));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Deletes the specified file in the file system. If the file doesn't exist the operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFile
* <pre>
* client.deleteFile&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFile
*
* @param fileName Name of the file to delete.
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteFile(String fileName) {
return deleteFileWithResponse(fileName, null).flatMap(FluxUtil::toMono);
}
/**
* Deletes the specified file in the directory. If the file doesn't exist the operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFileWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
*
* client.deleteFileWithResponse&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFileWithResponse
*
* @param fileName Name of the file to delete.
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteFileWithResponse(String fileName, DataLakeRequestConditions requestConditions) {
DataLakeFileAsyncClient dataLakeFileAsyncClient;
try {
dataLakeFileAsyncClient = getFileAsyncClient(fileName);
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
return dataLakeFileAsyncClient.deleteWithResponse(requestConditions);
}
/**
* Deletes the specified file in the file system if it exists.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFileIfExists
* <pre>
* client.deleteFileIfExists&
* if &
* System.out.println&
* &
* System.out.println&
* &
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFileIfExists
*
* @param fileName Name of the file to delete.
* @return a reactive response signaling completion. {@code true} indicates that the specified file was successfully
* deleted, {@code false} indicates that the specified file did not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> deleteFileIfExists(String fileName) {
return deleteFileIfExistsWithResponse(fileName, new DataLakePathDeleteOptions())
.map(response -> response.getStatusCode() != 404);
}
/**
* Deletes the specified file in the directory if it exists.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFileIfExistsWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* DataLakePathDeleteOptions options = new DataLakePathDeleteOptions&
* .setRequestConditions&
*
* client.deleteFileIfExistsWithResponse&
* if &
* System.out.println&
* &
* System.out.println&
* &
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFileIfExistsWithResponse
*
* @param fileName Name of the file to delete.
* @param options {@link DataLakePathDeleteOptions}
* @return A reactive response signaling completion. If {@link Response}'s status code is 200, the specified file was
* successfully deleted. If status code is 404, the specified file does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteFileIfExistsWithResponse(String fileName, DataLakePathDeleteOptions options) {
try {
return withContext(context -> this.deleteFileIfExistsWithResponse(fileName, options, context));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
Mono<Response<Void>> deleteFileIfExistsWithResponse(String fileName, DataLakePathDeleteOptions options,
Context context) {
try {
return getFileAsyncClient(fileName).deleteIfExistsWithResponse(options, context);
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Creates a new DataLakeDirectoryAsyncClient object by concatenating subdirectoryName to the end of
* DataLakeDirectoryAsyncClient's URL. The new DataLakeDirectoryAsyncClient uses the same request policy pipeline
* as the DataLakeDirectoryAsyncClient.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.getSubdirectoryAsyncClient
* <pre>
* DataLakeDirectoryAsyncClient dataLakeDirectoryClient = client.getSubdirectoryAsyncClient&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.getSubdirectoryAsyncClient
*
* @param subdirectoryName A {@code String} representing the name of the sub-directory.
* @return A new {@link DataLakeDirectoryAsyncClient} object which references the directory with the specified name
* in this file system.
*/
public DataLakeDirectoryAsyncClient getSubdirectoryAsyncClient(String subdirectoryName) {
Objects.requireNonNull(subdirectoryName, "'subdirectoryName' can not be set to null");
BlockBlobAsyncClient blockBlobAsyncClient = prepareBuilderAppendPath(subdirectoryName)
.buildBlockBlobAsyncClient();
String pathPrefix = getObjectPath().isEmpty() ? "" : getObjectPath() + "/";
return new DataLakeDirectoryAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(),
getAccountName(), getFileSystemName(),
Utility.urlEncode(pathPrefix + Utility.urlDecode(subdirectoryName)), blockBlobAsyncClient,
this.getSasToken());
}
/**
* Creates a new sub-directory within a directory. By default, this method will not overwrite an existing
* sub-directory. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectory
* <pre>
* DataLakeDirectoryAsyncClient directoryClient = client.createSubdirectory&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectory
*
* @param subdirectoryName Name of the sub-directory to create.
* @return A {@link Mono} containing a {@link DataLakeDirectoryAsyncClient} used to interact with the directory
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeDirectoryAsyncClient> createSubdirectory(String subdirectoryName) {
return createSubdirectory(subdirectoryName, false);
}
/**
* Creates a new sub-directory within a directory. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectory
* <pre>
* boolean overwrite = false; &
* DataLakeDirectoryAsyncClient dClient = client.createSubdirectory&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectory
*
* @param subdirectoryName Name of the sub-directory to create.
* @param overwrite Whether to overwrite, should the subdirectory exist.
* @return A {@link Mono} containing a {@link DataLakeDirectoryAsyncClient} used to interact with the directory
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeDirectoryAsyncClient> createSubdirectory(String subdirectoryName, boolean overwrite) {
DataLakeRequestConditions requestConditions = new DataLakeRequestConditions();
if (!overwrite) {
requestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return createSubdirectoryWithResponse(subdirectoryName, null, null, null, null, requestConditions)
.flatMap(FluxUtil::toMono);
}
/**
* Creates a new sub-directory within a directory. If a sub-directory with the same name already exists, the
* sub-directory will be overwritten. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectoryWithResponse
* <pre>
* PathHttpHeaders httpHeaders = new PathHttpHeaders&
* .setContentLanguage&
* .setContentType&
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* String permissions = "permissions";
* String umask = "umask";
* DataLakeDirectoryAsyncClient newDirectoryClient = client.createSubdirectoryWithResponse&
* directoryName, permissions, umask, httpHeaders, Collections.singletonMap&
* requestConditions
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectoryWithResponse
*
* @param subdirectoryName Name of the sub-directory to create.
* @param permissions POSIX access permissions for the sub-directory owner, the sub-directory owning group, and
* others.
* @param umask Restricts permissions of the sub-directory to be created.
* @param headers {@link PathHttpHeaders}
* @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeDirectoryAsyncClient} used to interact with the sub-directory created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeDirectoryAsyncClient>> createSubdirectoryWithResponse(String subdirectoryName,
String permissions, String umask, PathHttpHeaders headers, Map<String, String> metadata,
DataLakeRequestConditions requestConditions) {
DataLakeDirectoryAsyncClient dataLakeDirectoryAsyncClient;
try {
dataLakeDirectoryAsyncClient = getSubdirectoryAsyncClient(subdirectoryName);
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
return dataLakeDirectoryAsyncClient.createWithResponse(permissions, umask, headers, metadata, requestConditions)
.map(response -> new SimpleResponse<>(response, dataLakeDirectoryAsyncClient));
}
/**
* Creates a new subdirectory within a directory if it does not exist. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectoryIfNotExists
* <pre>
* DataLakeDirectoryAsyncClient subdirectoryClient = client.createSubdirectoryIfNotExists&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectoryIfNotExists
*
* @param subdirectoryName Name of the sub-directory to create.
* @return A {@link Mono} containing a {@link DataLakeDirectoryAsyncClient} used to interact with the subdirectory
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeDirectoryAsyncClient> createSubdirectoryIfNotExists(String subdirectoryName) {
return createSubdirectoryIfNotExistsWithResponse(subdirectoryName, new DataLakePathCreateOptions())
.flatMap(FluxUtil::toMono);
}
/**
* Creates a new sub-directory within a directory if it does not exist. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectoryIfNotExistsWithResponse
* <pre>
* PathHttpHeaders headers = new PathHttpHeaders&
* .setContentLanguage&
* .setContentType&
* String permissions = "permissions";
* String umask = "umask";
* DataLakePathCreateOptions options = new DataLakePathCreateOptions&
* .setPermissions&
*
* client.createSubdirectoryIfNotExistsWithResponse&
* if &
* System.out.println&
* &
* System.out.println&
* &
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectoryIfNotExistsWithResponse
*
* @param subdirectoryName Name of the subdirectory to create.
* @param options {@link DataLakePathCreateOptions}
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link DataLakeDirectoryAsyncClient} used to interact with the subdirectory created. If {@link Response}'s status
* code is 201, a new subdirectory was successfully created. If status code is 409, a subdirectory with the same
* name already existed at this location.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeDirectoryAsyncClient>> createSubdirectoryIfNotExistsWithResponse(
String subdirectoryName, DataLakePathCreateOptions options) {
options = options == null ? new DataLakePathCreateOptions() : options;
options.setRequestConditions(new DataLakeRequestConditions()
.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD));
try {
return createSubdirectoryWithResponse(subdirectoryName, options.getPermissions(), options.getUmask(),
options.getPathHttpHeaders(), options.getMetadata(), options.getRequestConditions())
.onErrorResume(t -> t instanceof DataLakeStorageException && ((DataLakeStorageException) t)
.getStatusCode() == 409,
t -> {
HttpResponse response = ((DataLakeStorageException) t).getResponse();
return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), getSubdirectoryAsyncClient(subdirectoryName)));
});
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Deletes the specified sub-directory in the directory. If the sub-directory doesn't exist or is not empty the
* operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectory
* <pre>
* client.deleteSubdirectory&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectory
*
* @param subdirectoryName Name of the sub-directory to delete.
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteSubdirectory(String subdirectoryName) {
return deleteSubdirectoryWithResponse(subdirectoryName, false, null).flatMap(FluxUtil::toMono);
}
/**
* Deletes the specified sub-directory in the directory. If the sub-directory doesn't exist or is not empty the
* operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectoryWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* boolean recursive = false; &
*
* client.deleteSubdirectoryWithResponse&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectoryWithResponse
*
* @param directoryName Name of the sub-directory to delete.
* @param recursive Whether to delete all paths beneath the sub-directory.
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubdirectoryWithResponse(String directoryName, boolean recursive,
DataLakeRequestConditions requestConditions) {
DataLakeDirectoryAsyncClient dataLakeDirectoryAsyncClient;
try {
dataLakeDirectoryAsyncClient = getSubdirectoryAsyncClient(directoryName);
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
return dataLakeDirectoryAsyncClient.deleteWithResponse(recursive, requestConditions);
}
/**
* Deletes the specified subdirectory in the directory if it exists.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectoryIfExists
* <pre>
* client.deleteSubdirectoryIfExists&
* if &
* System.out.println&
* &
* System.out.println&
* &
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectoryIfExists
*
* @param subdirectoryName Name of the subdirectory to delete.
* @return A reactive response signaling completion. {@code true} indicates that the subdirectory was deleted.
* {@code false} indicates the specified subdirectory does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> deleteSubdirectoryIfExists(String subdirectoryName) {
return deleteSubdirectoryIfExistsWithResponse(subdirectoryName, new DataLakePathDeleteOptions())
.map(response -> response.getStatusCode() != 404);
}
/**
* Deletes the specified subdirectory in the directory if it exists.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectoryIfExistsWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* boolean recursive = false; &
* DataLakePathDeleteOptions options = new DataLakePathDeleteOptions&
* .setRequestConditions&
*
* client.deleteSubdirectoryIfExistsWithResponse&
* if &
* System.out.println&
* &
* System.out.println&
* &
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectoryIfExistsWithResponse
*
* @param directoryName Name of the subdirectory to delete.
* @param options {@link DataLakePathDeleteOptions}
* @return A reactive response signaling completion. If {@link Response}'s status code is 200, the specified subdirectory
* was successfully deleted. If status code is 404, the specified subdirectory does not exist.
*
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubdirectoryIfExistsWithResponse(String directoryName,
DataLakePathDeleteOptions options) {
try {
return deleteSubdirectoryWithResponse(directoryName, options.getIsRecursive(),
options.getRequestConditions())
.onErrorResume(t -> t instanceof DataLakeStorageException
&& ((DataLakeStorageException) t).getStatusCode() == 404,
t -> {
HttpResponse response = ((DataLakeStorageException) t).getResponse();
return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
});
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Moves the directory to another location within the file system.
* For more information see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.rename
* <pre>
* DataLakeDirectoryAsyncClient renamedClient = client.rename&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.rename
*
* @param destinationFileSystem The file system of the destination within the account.
* {@code null} for the current file system.
* @param destinationPath Relative path from the file system to rename the directory to, excludes the file system
* name. For example if you want to move a directory with fileSystem = "myfilesystem", path = "mydir/mysubdir" to
* another path in myfilesystem (ex: newdir) then set the destinationPath = "newdir"
* @return A {@link Mono} containing a {@link DataLakeDirectoryAsyncClient} used to interact with the new directory
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeDirectoryAsyncClient> rename(String destinationFileSystem, String destinationPath) {
return renameWithResponse(destinationFileSystem, destinationPath, null, null).flatMap(FluxUtil::toMono);
}
/**
* Moves the directory to another location within the file system.
* For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.renameWithResponse
* <pre>
* DataLakeRequestConditions sourceRequestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* DataLakeRequestConditions destinationRequestConditions = new DataLakeRequestConditions&
*
* DataLakeDirectoryAsyncClient newRenamedClient = client.renameWithResponse&
* sourceRequestConditions, destinationRequestConditions&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.renameWithResponse
*
* @param destinationFileSystem The file system of the destination within the account.
* {@code null} for the current file system.
* @param destinationPath Relative path from the file system to rename the directory to, excludes the file system
* name. For example if you want to move a directory with fileSystem = "myfilesystem", path = "mydir/mysubdir" to
* another path in myfilesystem (ex: newdir) then set the destinationPath = "newdir"
* @param sourceRequestConditions {@link DataLakeRequestConditions} against the source.
* @param destinationRequestConditions {@link DataLakeRequestConditions} against the destination.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeDirectoryAsyncClient} used to interact with the directory created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeDirectoryAsyncClient>> renameWithResponse(String destinationFileSystem,
String destinationPath, DataLakeRequestConditions sourceRequestConditions,
DataLakeRequestConditions destinationRequestConditions) {
try {
return withContext(context -> renameWithResponse(destinationFileSystem, destinationPath,
sourceRequestConditions, destinationRequestConditions, context)).map(
response -> new SimpleResponse<>(response, new DataLakeDirectoryAsyncClient(response.getValue())));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Returns a reactive Publisher emitting all the files/directories in this directory lazily as needed. For more
* information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.listPaths -->
* <pre>
* client.listPaths&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.listPaths -->
*
* @return A reactive response emitting the list of files/directories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<PathItem> listPaths() {
return this.listPaths(false, false, null);
}
/**
* Returns a reactive Publisher emitting all the files/directories in this directory lazily as needed. For more
* information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.listPaths
* <pre>
* client.listPaths&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.listPaths
*
* @param recursive Specifies if the call should recursively include all paths.
* @param userPrincipleNameReturned If "true", the user identity values returned by the x-ms-owner, x-ms-group,
* and x-ms-acl response headers will be transformed from Azure Active Directory Object IDs to User Principal Names.
* If "false", the values will be returned as Azure Active Directory Object IDs.
* The default value is false. Note that group and application Object IDs are not translated because they do not
* have unique friendly names.
* @param maxResults Specifies the maximum number of blobs to return per page, including all BlobPrefix elements. If
* the request does not specify maxResults or specifies a value greater than 5,000, the server will return up to
* 5,000 items per page.
* @return A reactive response emitting the list of files/directories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<PathItem> listPaths(boolean recursive, boolean userPrincipleNameReturned, Integer maxResults) {
try {
return listPathsWithOptionalTimeout(recursive, userPrincipleNameReturned, maxResults, null);
} catch (RuntimeException ex) {
return pagedFluxError(LOGGER, ex);
}
}
PagedFlux<PathItem> listPathsWithOptionalTimeout(boolean recursive, boolean userPrincipleNameReturned,
Integer maxResults, Duration timeout) {
BiFunction<String, Integer, Mono<PagedResponse<PathItem>>> func =
(marker, pageSize) -> listPathsSegment(marker, recursive, userPrincipleNameReturned,
pageSize == null ? maxResults : pageSize, timeout)
.map(response -> {
List<PathItem> value = response.getValue() == null
? Collections.emptyList()
: response.getValue().getPaths().stream()
.map(Transforms::toPathItem)
.collect(Collectors.toList());
return new PagedResponseBase<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
value,
response.getDeserializedHeaders().getXMsContinuation(),
response.getDeserializedHeaders());
});
return new PagedFlux<>(pageSize -> func.apply(null, pageSize), func);
}
private Mono<FileSystemsListPathsResponse> listPathsSegment(String marker, boolean recursive,
boolean userPrincipleNameReturned, Integer maxResults, Duration timeout) {
return StorageImplUtils.applyOptionalTimeout(
this.fileSystemDataLakeStorage.getFileSystems().listPathsWithResponseAsync(
recursive, null, null, marker, getDirectoryPath(), maxResults, userPrincipleNameReturned,
Context.NONE), timeout);
}
/**
* Prepares a SpecializedBlobClientBuilder with the pathname appended to the end of the current BlockBlobClient's
* url
* @param pathName The name of the path to append
* @return {@link SpecializedBlobClientBuilder}
*/
SpecializedBlobClientBuilder prepareBuilderAppendPath(String pathName) {
String blobUrl = DataLakeImplUtils.endpointToDesiredEndpoint(getPathUrl(), "blob", "dfs");
return new SpecializedBlobClientBuilder()
.pipeline(getHttpPipeline())
.serviceVersion(TransformUtils.toBlobServiceVersion(getServiceVersion()))
.endpoint(StorageImplUtils.appendToUrlPath(blobUrl, pathName).toString());
}
} |
This should apply to delete as well | public Mono<Response<DataLakeFileAsyncClient>> createFileIfNotExistsWithResponse(String fileName, String permissions, String umask, PathHttpHeaders headers, Map<String, String> metadata, Context context) {
DataLakeRequestConditions requestConditions = new DataLakeRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
DataLakeFileAsyncClient dataLakeFileAsyncClient = getFileAsyncClient(fileName);
return dataLakeFileAsyncClient.createWithResponse(permissions, umask, pathResourceType,
headers, metadata, requestConditions, context).onErrorResume(t -> t instanceof DataLakeStorageException && ((DataLakeStorageException) t).getStatusCode() == 409, t -> Mono.empty())
.map(response -> new SimpleResponse<>(response, dataLakeFileAsyncClient));
} | return dataLakeFileAsyncClient.createWithResponse(permissions, umask, pathResourceType, | new DataLakeRequestConditions();
if (!overwrite) {
requestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
} | class DataLakeDirectoryAsyncClient extends DataLakePathAsyncClient {
private final ClientLogger logger = new ClientLogger(DataLakeDirectoryAsyncClient.class);
/**
* Package-private constructor for use by {@link DataLakePathClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param fileSystemName The file system name.
* @param directoryName The directory name.
* @param blockBlobAsyncClient The underlying {@link BlobContainerAsyncClient}
*/
DataLakeDirectoryAsyncClient(HttpPipeline pipeline, String url, DataLakeServiceVersion serviceVersion,
String accountName, String fileSystemName, String directoryName, BlockBlobAsyncClient blockBlobAsyncClient) {
super(pipeline, url, serviceVersion, accountName, fileSystemName, directoryName, PathResourceType.DIRECTORY,
blockBlobAsyncClient);
}
DataLakeDirectoryAsyncClient(DataLakePathAsyncClient dataLakePathAsyncClient) {
super(dataLakePathAsyncClient.getHttpPipeline(), dataLakePathAsyncClient.getAccountUrl(),
dataLakePathAsyncClient.getServiceVersion(), dataLakePathAsyncClient.getAccountName(),
dataLakePathAsyncClient.getFileSystemName(), Utility.urlEncode(dataLakePathAsyncClient.pathName),
PathResourceType.DIRECTORY, dataLakePathAsyncClient.getBlockBlobAsyncClient());
}
/**
* Gets the URL of the directory represented by this client on the Data Lake service.
*
* @return the URL.
*/
public String getDirectoryUrl() {
return getPathUrl();
}
/**
* Gets the path of this directory, not including the name of the resource itself.
*
* @return The path of the directory.
*/
public String getDirectoryPath() {
return getObjectPath();
}
/**
* Gets the name of this directory, not including its full path.
*
* @return The name of the directory.
*/
public String getDirectoryName() {
return getObjectName();
}
/**
* Deletes a directory.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.delete -->
* <pre>
* client.delete&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.delete -->
*
* <p>For more information see the
* <a href="https:
* Docs</a></p>
*
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> delete() {
try {
return deleteWithResponse(false, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a directory.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* boolean recursive = false; &
*
* client.deleteWithResponse&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteWithResponse
*
* <p>For more information see the
* <a href="https:
* Docs</a></p>
*
* @param recursive Whether or not to delete all paths beneath the directory.
* @param requestConditions {@link DataLakeRequestConditions}
*
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteWithResponse(boolean recursive, DataLakeRequestConditions requestConditions) {
try {
return withContext(context -> deleteWithResponse(recursive, requestConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new DataLakeFileAsyncClient object by concatenating fileName to the end of
* DataLakeDirectoryAsyncClient's URL. The new DataLakeFileAsyncClient uses the same request policy pipeline as the
* DataLakeDirectoryAsyncClient.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.getFileAsyncClient
* <pre>
* DataLakeFileAsyncClient dataLakeFileClient = client.getFileAsyncClient&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.getFileAsyncClient
*
* @param fileName A {@code String} representing the name of the file.
* @return A new {@link DataLakeFileAsyncClient} object which references the file with the specified name in this
* file system.
*/
public DataLakeFileAsyncClient getFileAsyncClient(String fileName) {
Objects.requireNonNull(fileName, "'fileName' can not be set to null");
BlockBlobAsyncClient blockBlobAsyncClient = prepareBuilderAppendPath(fileName).buildBlockBlobAsyncClient();
String pathPrefix = getObjectPath().isEmpty() ? "" : getObjectPath() + "/";
return new DataLakeFileAsyncClient(getHttpPipeline(), getAccountUrl(),
getServiceVersion(), getAccountName(), getFileSystemName(), Utility.urlEncode(pathPrefix
+ Utility.urlDecode(fileName)), blockBlobAsyncClient);
}
/**
* Creates a new file within a directory. By default this method will not overwrite an existing file.
* For more information, see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFile
* <pre>
* DataLakeFileAsyncClient fileClient = client.createFile&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFile
*
* @param fileName Name of the file to create.
* @return A {@link Mono} containing a {@link DataLakeFileAsyncClient} used to interact with the file created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileAsyncClient> createFile(String fileName) {
return createFile(fileName, false);
}
/**
* Creates a new file within a directory. For more information, see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFile
* <pre>
* boolean overwrite = false; &
* DataLakeFileAsyncClient fClient = client.createFile&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFile
*
* @param fileName Name of the file to create.
* @param overwrite Whether or not to overwrite, should the file exist.
* @return A {@link Mono} containing a {@link DataLakeFileAsyncClient} used to interact with the file created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileAsyncClient> createFile(String fileName, boolean overwrite) {
DataLakeRequestConditions requestConditions =
try {
return createFileWithResponse(fileName, null, null, null, null, requestConditions)
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new file within a directory. If a file with the same name already exists, the file will be
* overwritten. For more information, see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFileWithResponse
* <pre>
* PathHttpHeaders httpHeaders = new PathHttpHeaders&
* .setContentLanguage&
* .setContentType&
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* String permissions = "permissions";
* String umask = "umask";
* DataLakeFileAsyncClient newFileClient = client.createFileWithResponse&
* permissions, umask, httpHeaders, Collections.singletonMap&
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFileWithResponse
*
* @param fileName Name of the file to create.
* @param permissions POSIX access permissions for the file owner, the file owning group, and others.
* @param umask Restricts permissions of the file to be created.
* @param headers {@link PathHttpHeaders}
* @param metadata Metadata to associate with the file. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeFileAsyncClient} used to interact with the file created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileAsyncClient>> createFileWithResponse(String fileName, String permissions,
String umask, PathHttpHeaders headers, Map<String, String> metadata,
DataLakeRequestConditions requestConditions) {
try {
DataLakeFileAsyncClient dataLakeFileAsyncClient = getFileAsyncClient(fileName);
return dataLakeFileAsyncClient.createWithResponse(permissions, umask, headers, metadata, requestConditions)
.map(response -> new SimpleResponse<>(response, dataLakeFileAsyncClient));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileAsyncClient> createFileIfNotExists(String fileName) {
return createFileIfNotExistsWithResponse(fileName, null, null, null, null).flatMap(FluxUtil::toMono);
}
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileAsyncClient>> createFileIfNotExistsWithResponse(String fileName, String permissions,
String umask, PathHttpHeaders headers, Map<String, String> metadata) {
return createFileIfNotExistsWithResponse(fileName, permissions, umask, headers, metadata, null);
}
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileAsyncClient>> createFileIfNotExistsWithResponse(String fileName, String permissions, String umask, PathHttpHeaders headers, Map<String, String> metadata, Context context) {
DataLakeRequestConditions requestConditions = new DataLakeRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
DataLakeFileAsyncClient dataLakeFileAsyncClient = getFileAsyncClient(fileName);
return dataLakeFileAsyncClient.createWithResponse(permissions, umask, pathResourceType,
headers, metadata, requestConditions, context).onErrorResume(t -> t instanceof DataLakeStorageException && ((DataLakeStorageException) t).getStatusCode() == 409, t -> Mono.empty())
.map(response -> new SimpleResponse<>(response, dataLakeFileAsyncClient));
}
/*
Mono<Response<AppendBlobItem>> createIfNotExistsWithResponse(AppendBlobCreateOptions options, Context context) {
options.setRequestConditions(new AppendBlobRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD));
return createWithResponse(options, context).onErrorResume(t -> t instanceof BlobStorageException && ((BlobStorageException) t).getStatusCode() == 409,
t -> Mono.empty());
}
.onErrorResume(t -> instanceof DataLakeStorageException && ((DataLakeStorageException) t).getStatusCode() == 409,
*/
/**
* Deletes the specified file in the file system. If the file doesn't exist the operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFile
* <pre>
* client.deleteFile&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFile
*
* @param fileName Name of the file to delete.
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteFile(String fileName) {
try {
return deleteFileWithResponse(fileName, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified file in the directory. If the file doesn't exist the operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFileWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
*
* client.deleteFileWithResponse&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFileWithResponse
*
* @param fileName Name of the file to delete.
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteFileWithResponse(String fileName, DataLakeRequestConditions requestConditions) {
try {
return getFileAsyncClient(fileName).deleteWithResponse(requestConditions);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteFileIfExists(String fileName) {
try {
return deleteFileIfExistsWithResponse(fileName, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteFileIfExistsWithResponse(String fileName, DataLakeRequestConditions requestConditions) {
return deleteFileIfExistsWithResponse(fileName, requestConditions, null);
}
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteFileIfExistsWithResponse(String fileName, DataLakeRequestConditions requestConditions, Context context) {
return getFileAsyncClient(fileName).deleteWithResponse(null, requestConditions, context)
.onErrorResume(t -> t instanceof DataLakeStorageException && ((DataLakeStorageException)t).getStatusCode() == 404,
t -> Mono.empty());
}
/**
* Creates a new DataLakeDirectoryAsyncClient object by concatenating subdirectoryName to the end of
* DataLakeDirectoryAsyncClient's URL. The new DataLakeDirectoryAsyncClient uses the same request policy pipeline
* as the DataLakeDirectoryAsyncClient.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.getSubdirectoryAsyncClient
* <pre>
* DataLakeDirectoryAsyncClient dataLakeDirectoryClient = client.getSubdirectoryAsyncClient&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.getSubdirectoryAsyncClient
*
* @param subdirectoryName A {@code String} representing the name of the sub-directory.
* @return A new {@link DataLakeDirectoryAsyncClient} object which references the directory with the specified name
* in this file system.
*/
public DataLakeDirectoryAsyncClient getSubdirectoryAsyncClient(String subdirectoryName) {
Objects.requireNonNull(subdirectoryName, "'subdirectoryName' can not be set to null");
BlockBlobAsyncClient blockBlobAsyncClient = prepareBuilderAppendPath(subdirectoryName)
.buildBlockBlobAsyncClient();
String pathPrefix = getObjectPath().isEmpty() ? "" : getObjectPath() + "/";
return new DataLakeDirectoryAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(),
getAccountName(), getFileSystemName(),
Utility.urlEncode(pathPrefix + Utility.urlDecode(subdirectoryName)), blockBlobAsyncClient);
}
/**
* Creates a new sub-directory within a directory. By default this method will not overwrite an existing
* sub-directory. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectory
* <pre>
* DataLakeDirectoryAsyncClient directoryClient = client.createSubdirectory&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectory
*
* @param subdirectoryName Name of the sub-directory to create.
* @return A {@link Mono} containing a {@link DataLakeDirectoryAsyncClient} used to interact with the directory
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeDirectoryAsyncClient> createSubdirectory(String subdirectoryName) {
return createSubdirectory(subdirectoryName, false);
}
/**
* Creates a new sub-directory within a directory. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectory
* <pre>
* boolean overwrite = false; &
* DataLakeDirectoryAsyncClient dClient = client.createSubdirectory&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectory
*
* @param subdirectoryName Name of the sub-directory to create.
* @param overwrite Whether or not to overwrite, should the sub directory exist.
* @return A {@link Mono} containing a {@link DataLakeDirectoryAsyncClient} used to interact with the directory
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeDirectoryAsyncClient> createSubdirectory(String subdirectoryName, boolean overwrite) {
DataLakeRequestConditions requestConditions = new DataLakeRequestConditions();
if (!overwrite) {
requestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
try {
return createSubdirectoryWithResponse(subdirectoryName, null, null, null, null, requestConditions)
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new sub-directory within a directory. If a sub-directory with the same name already exists, the
* sub-directory will be overwritten. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectoryWithResponse
* <pre>
* PathHttpHeaders httpHeaders = new PathHttpHeaders&
* .setContentLanguage&
* .setContentType&
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* String permissions = "permissions";
* String umask = "umask";
* DataLakeDirectoryAsyncClient newDirectoryClient = client.createSubdirectoryWithResponse&
* directoryName, permissions, umask, httpHeaders, Collections.singletonMap&
* requestConditions
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectoryWithResponse
*
* @param subdirectoryName Name of the sub-directory to create.
* @param permissions POSIX access permissions for the sub-directory owner, the sub-directory owning group, and
* others.
* @param umask Restricts permissions of the sub-directory to be created.
* @param headers {@link PathHttpHeaders}
* @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeDirectoryAsyncClient} used to interact with the sub-directory created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeDirectoryAsyncClient>> createSubdirectoryWithResponse(String subdirectoryName,
String permissions, String umask, PathHttpHeaders headers, Map<String, String> metadata,
DataLakeRequestConditions requestConditions) {
try {
DataLakeDirectoryAsyncClient dataLakeDirectoryAsyncClient = getSubdirectoryAsyncClient(subdirectoryName);
return dataLakeDirectoryAsyncClient.createWithResponse(permissions, umask, headers, metadata,
requestConditions).map(response -> new SimpleResponse<>(response, dataLakeDirectoryAsyncClient));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified sub-directory in the directory. If the sub-directory doesn't exist or is not empty the
* operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectory
* <pre>
* client.deleteSubdirectory&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectory
*
* @param subdirectoryName Name of the sub-directory to delete.
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteSubdirectory(String subdirectoryName) {
try {
return deleteSubdirectoryWithResponse(subdirectoryName, false, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified sub-directory in the directory. If the sub-directory doesn't exist or is not empty the
* operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectoryWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* boolean recursive = false; &
*
* client.deleteSubdirectoryWithResponse&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectoryWithResponse
*
* @param directoryName Name of the sub-directory to delete.
* @param recursive Whether or not to delete all paths beneath the sub-directory.
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubdirectoryWithResponse(String directoryName, boolean recursive,
DataLakeRequestConditions requestConditions) {
try {
return getSubdirectoryAsyncClient(directoryName).deleteWithResponse(recursive, requestConditions);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Moves the directory to another location within the file system.
* For more information see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.rename
* <pre>
* DataLakeDirectoryAsyncClient renamedClient = client.rename&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.rename
*
* @param destinationFileSystem The file system of the destination within the account.
* {@code null} for the current file system.
* @param destinationPath Relative path from the file system to rename the directory to, excludes the file system
* name. For example if you want to move a directory with fileSystem = "myfilesystem", path = "mydir/mysubdir" to
* another path in myfilesystem (ex: newdir) then set the destinationPath = "newdir"
* @return A {@link Mono} containing a {@link DataLakeDirectoryAsyncClient} used to interact with the new directory
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeDirectoryAsyncClient> rename(String destinationFileSystem, String destinationPath) {
try {
return renameWithResponse(destinationFileSystem, destinationPath, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Moves the directory to another location within the file system.
* For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.renameWithResponse
* <pre>
* DataLakeRequestConditions sourceRequestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* DataLakeRequestConditions destinationRequestConditions = new DataLakeRequestConditions&
*
* DataLakeDirectoryAsyncClient newRenamedClient = client.renameWithResponse&
* sourceRequestConditions, destinationRequestConditions&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.renameWithResponse
*
* @param destinationFileSystem The file system of the destination within the account.
* {@code null} for the current file system.
* @param destinationPath Relative path from the file system to rename the directory to, excludes the file system
* name. For example if you want to move a directory with fileSystem = "myfilesystem", path = "mydir/mysubdir" to
* another path in myfilesystem (ex: newdir) then set the destinationPath = "newdir"
* @param sourceRequestConditions {@link DataLakeRequestConditions} against the source.
* @param destinationRequestConditions {@link DataLakeRequestConditions} against the destination.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeDirectoryAsyncClient} used to interact with the directory created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeDirectoryAsyncClient>> renameWithResponse(String destinationFileSystem,
String destinationPath, DataLakeRequestConditions sourceRequestConditions,
DataLakeRequestConditions destinationRequestConditions) {
try {
return withContext(context -> renameWithResponse(destinationFileSystem, destinationPath,
sourceRequestConditions, destinationRequestConditions, context)).map(
response -> new SimpleResponse<>(response, new DataLakeDirectoryAsyncClient(response.getValue())));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Returns a reactive Publisher emitting all the files/directories in this directory lazily as needed. For more
* information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.listPaths -->
* <pre>
* client.listPaths&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.listPaths -->
*
* @return A reactive response emitting the list of files/directories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<PathItem> listPaths() {
return this.listPaths(false, false, null);
}
/**
* Returns a reactive Publisher emitting all the files/directories in this directory lazily as needed. For more
* information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.listPaths
* <pre>
* client.listPaths&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.listPaths
*
* @param recursive Specifies if the call should recursively include all paths.
* @param userPrincipleNameReturned If "true", the user identity values returned in the x-ms-owner, x-ms-group,
* and x-ms-acl response headers will be transformed from Azure Active Directory Object IDs to User Principal Names.
* If "false", the values will be returned as Azure Active Directory Object IDs.
* The default value is false. Note that group and application Object IDs are not translated because they do not
* have unique friendly names.
* @param maxResults Specifies the maximum number of blobs to return per page, including all BlobPrefix elements. If
* the request does not specify maxResults or specifies a value greater than 5,000, the server will return up to
* 5,000 items per page.
* @return A reactive response emitting the list of files/directories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<PathItem> listPaths(boolean recursive, boolean userPrincipleNameReturned, Integer maxResults) {
try {
return listPathsWithOptionalTimeout(recursive, userPrincipleNameReturned, maxResults, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<PathItem> listPathsWithOptionalTimeout(boolean recursive, boolean userPrincipleNameReturned,
Integer maxResults, Duration timeout) {
BiFunction<String, Integer, Mono<PagedResponse<PathItem>>> func =
(marker, pageSize) -> listPathsSegment(marker, recursive, userPrincipleNameReturned,
pageSize == null ? maxResults : pageSize, timeout)
.map(response -> {
List<PathItem> value = response.getValue() == null
? Collections.emptyList()
: response.getValue().getPaths().stream()
.map(Transforms::toPathItem)
.collect(Collectors.toList());
return new PagedResponseBase<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
value,
response.getDeserializedHeaders().getXMsContinuation(),
response.getDeserializedHeaders());
});
return new PagedFlux<>(pageSize -> func.apply(null, pageSize), func);
}
private Mono<FileSystemsListPathsResponse> listPathsSegment(String marker, boolean recursive,
boolean userPrincipleNameReturned, Integer maxResults, Duration timeout) {
return StorageImplUtils.applyOptionalTimeout(
this.fileSystemDataLakeStorage.getFileSystems().listPathsWithResponseAsync(
recursive, null, null, marker, getDirectoryPath(), maxResults, userPrincipleNameReturned,
Context.NONE), timeout);
}
/**
* Prepares a SpecializedBlobClientBuilder with the pathname appended to the end of the current BlockBlobClient's
* url
* @param pathName The name of the path to append
* @return {@link SpecializedBlobClientBuilder}
*/
SpecializedBlobClientBuilder prepareBuilderAppendPath(String pathName) {
String blobUrl = DataLakeImplUtils.endpointToDesiredEndpoint(getPathUrl(), "blob", "dfs");
return new SpecializedBlobClientBuilder()
.pipeline(getHttpPipeline())
.serviceVersion(TransformUtils.toBlobServiceVersion(getServiceVersion()))
.endpoint(StorageImplUtils.appendToUrlPath(blobUrl, pathName).toString());
}
} | class DataLakeDirectoryAsyncClient extends DataLakePathAsyncClient {
private static final ClientLogger LOGGER = new ClientLogger(DataLakeDirectoryAsyncClient.class);
/**
* Package-private constructor for use by {@link DataLakePathClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param fileSystemName The file system name.
* @param directoryName The directory name.
* @param blockBlobAsyncClient The underlying {@link BlobContainerAsyncClient}
*/
DataLakeDirectoryAsyncClient(HttpPipeline pipeline, String url, DataLakeServiceVersion serviceVersion,
String accountName, String fileSystemName, String directoryName, BlockBlobAsyncClient blockBlobAsyncClient,
AzureSasCredential sasToken) {
super(pipeline, url, serviceVersion, accountName, fileSystemName, directoryName, PathResourceType.DIRECTORY,
blockBlobAsyncClient, sasToken);
}
DataLakeDirectoryAsyncClient(DataLakePathAsyncClient dataLakePathAsyncClient) {
super(dataLakePathAsyncClient.getHttpPipeline(), dataLakePathAsyncClient.getAccountUrl(),
dataLakePathAsyncClient.getServiceVersion(), dataLakePathAsyncClient.getAccountName(),
dataLakePathAsyncClient.getFileSystemName(), Utility.urlEncode(dataLakePathAsyncClient.pathName),
PathResourceType.DIRECTORY, dataLakePathAsyncClient.getBlockBlobAsyncClient(),
dataLakePathAsyncClient.getSasToken());
}
/**
* Gets the URL of the directory represented by this client on the Data Lake service.
*
* @return the URL.
*/
public String getDirectoryUrl() {
return getPathUrl();
}
/**
* Gets the path of this directory, not including the name of the resource itself.
*
* @return The path of the directory.
*/
public String getDirectoryPath() {
return getObjectPath();
}
/**
* Gets the name of this directory, not including its full path.
*
* @return The name of the directory.
*/
public String getDirectoryName() {
return getObjectName();
}
/**
* Deletes a directory.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.delete -->
* <pre>
* client.delete&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.delete -->
*
* <p>For more information see the
* <a href="https:
* Docs</a></p>
*
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> delete() {
return deleteWithResponse(false, null).flatMap(FluxUtil::toMono);
}
/**
* Deletes a directory.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* boolean recursive = false; &
*
* client.deleteWithResponse&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteWithResponse
*
* <p>For more information see the
* <a href="https:
* Docs</a></p>
*
* @param recursive Whether to delete all paths beneath the directory.
* @param requestConditions {@link DataLakeRequestConditions}
*
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteWithResponse(boolean recursive, DataLakeRequestConditions requestConditions) {
try {
return withContext(context -> deleteWithResponse(recursive, requestConditions, context));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Deletes a directory if it exists.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteIfExists -->
* <pre>
* client.deleteIfExists&
* if &
* System.out.println&
* &
* System.out.println&
* &
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteIfExists -->
*
* <p>For more information see the
* <a href="https:
* Docs</a></p>
*
* @return a reactive response signaling completion. {@code true} indicates that the directory was successfully
* deleted, {@code true} indicates that the directory did not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> deleteIfExists() {
return deleteIfExistsWithResponse(new DataLakePathDeleteOptions())
.map(response -> response.getStatusCode() != 404);
}
/**
* Deletes a directory if it exists.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteIfExistsWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* boolean recursive = false; &
* DataLakePathDeleteOptions options = new DataLakePathDeleteOptions&
* .setRequestConditions&
*
* client.deleteIfExistsWithResponse&
* if &
* System.out.println&
* &
* System.out.println&
* &
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteIfExistsWithResponse
*
* <p>For more information see the
* <a href="https:
* Docs</a></p>
*
* @param options {@link DataLakePathDeleteOptions}
*
* @return A reactive response signaling completion. If {@link Response}'s status code is 200, the directory was
* successfully deleted. If status code is 404, the directory does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteIfExistsWithResponse(DataLakePathDeleteOptions options) {
try {
options = options == null ? new DataLakePathDeleteOptions() : options;
return deleteWithResponse(options.getIsRecursive(), options.getRequestConditions()).onErrorResume(t -> t
instanceof DataLakeStorageException && ((DataLakeStorageException) t).getStatusCode() == 404,
t -> {
HttpResponse response = ((DataLakeStorageException) t).getResponse();
return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
});
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Creates a new DataLakeFileAsyncClient object by concatenating fileName to the end of
* DataLakeDirectoryAsyncClient's URL. The new DataLakeFileAsyncClient uses the same request policy pipeline as the
* DataLakeDirectoryAsyncClient.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.getFileAsyncClient
* <pre>
* DataLakeFileAsyncClient dataLakeFileClient = client.getFileAsyncClient&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.getFileAsyncClient
*
* @param fileName A {@code String} representing the name of the file.
* @return A new {@link DataLakeFileAsyncClient} object which references the file with the specified name in this
* file system.
*/
public DataLakeFileAsyncClient getFileAsyncClient(String fileName) {
Objects.requireNonNull(fileName, "'fileName' can not be set to null");
BlockBlobAsyncClient blockBlobAsyncClient = prepareBuilderAppendPath(fileName).buildBlockBlobAsyncClient();
String pathPrefix = getObjectPath().isEmpty() ? "" : getObjectPath() + "/";
return new DataLakeFileAsyncClient(getHttpPipeline(), getAccountUrl(),
getServiceVersion(), getAccountName(), getFileSystemName(), Utility.urlEncode(pathPrefix
+ Utility.urlDecode(fileName)), blockBlobAsyncClient, this.getSasToken());
}
/**
* Creates a new file within a directory. By default, this method will not overwrite an existing file.
* For more information, see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFile
* <pre>
* DataLakeFileAsyncClient fileClient = client.createFile&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFile
*
* @param fileName Name of the file to create.
* @return A {@link Mono} containing a {@link DataLakeFileAsyncClient} used to interact with the file created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileAsyncClient> createFile(String fileName) {
return createFile(fileName, false);
}
/**
* Creates a new file within a directory. For more information, see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFile
* <pre>
* boolean overwrite = false; &
* DataLakeFileAsyncClient fClient = client.createFile&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFile
*
* @param fileName Name of the file to create.
* @param overwrite Whether to overwrite, should the file exist.
* @return A {@link Mono} containing a {@link DataLakeFileAsyncClient} used to interact with the file created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileAsyncClient> createFile(String fileName, boolean overwrite) {
DataLakeRequestConditions requestConditions =
return createFileWithResponse(fileName, null, null, null, null, requestConditions).flatMap(FluxUtil::toMono);
}
/**
* Creates a new file within a directory. If a file with the same name already exists, the file will be
* overwritten. For more information, see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFileWithResponse
* <pre>
* PathHttpHeaders httpHeaders = new PathHttpHeaders&
* .setContentLanguage&
* .setContentType&
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* String permissions = "permissions";
* String umask = "umask";
* DataLakeFileAsyncClient newFileClient = client.createFileWithResponse&
* permissions, umask, httpHeaders, Collections.singletonMap&
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFileWithResponse
*
* @param fileName Name of the file to create.
* @param permissions POSIX access permissions for the file owner, the file owning group, and others.
* @param umask Restricts permissions of the file to be created.
* @param headers {@link PathHttpHeaders}
* @param metadata Metadata to associate with the file. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeFileAsyncClient} used to interact with the file created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileAsyncClient>> createFileWithResponse(String fileName, String permissions,
String umask, PathHttpHeaders headers, Map<String, String> metadata,
DataLakeRequestConditions requestConditions) {
DataLakeFileAsyncClient dataLakeFileAsyncClient;
try {
dataLakeFileAsyncClient = getFileAsyncClient(fileName);
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
return dataLakeFileAsyncClient.createWithResponse(permissions, umask, headers, metadata, requestConditions)
.map(response -> new SimpleResponse<>(response, dataLakeFileAsyncClient));
}
/**
* Creates a new file within a directory if it does not exist. By default this method will not overwrite an existing
* file. For more information, see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFileIfNotExists
* <pre>
* DataLakeFileAsyncClient fileClient = client.createFileIfNotExists&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFileIfNotExists
*
* @param fileName Name of the file to create.
* @return A {@link Mono} containing a {@link DataLakeFileAsyncClient} used to interact with the file created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileAsyncClient> createFileIfNotExists(String fileName) {
return createFileIfNotExistsWithResponse(fileName, new DataLakePathCreateOptions()).flatMap(FluxUtil::toMono);
}
/**
* Creates a new file within a directory if it does not exist. For more information, see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFileIfNotExistsWithResponse
* <pre>
* PathHttpHeaders headers = new PathHttpHeaders&
* .setContentLanguage&
* .setContentType&
* String permissions = "permissions";
* String umask = "umask";
* DataLakePathCreateOptions options = new DataLakePathCreateOptions&
* .setPermissions&
*
* client.createFileIfNotExistsWithResponse&
* if &
* System.out.println&
* &
* System.out.println&
* &
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createFileIfNotExistsWithResponse
*
* @param fileName Name of the file to create.
* @param options {@link DataLakePathCreateOptions}
* metadata key or value, it must be removed or encoded.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link DataLakeFileAsyncClient} used to interact with the file created. If {@link Response}'s status code is 201,
* a new file was successfully created. If status code is 409, a file with the same name already existed
* at this location.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileAsyncClient>> createFileIfNotExistsWithResponse(String fileName,
DataLakePathCreateOptions options) {
DataLakeFileAsyncClient dataLakeFileAsyncClient = getFileAsyncClient(fileName);
try {
return dataLakeFileAsyncClient.createIfNotExistsWithResponse(options)
.map(response -> new SimpleResponse<>(response, dataLakeFileAsyncClient));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Deletes the specified file in the file system. If the file doesn't exist the operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFile
* <pre>
* client.deleteFile&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFile
*
* @param fileName Name of the file to delete.
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteFile(String fileName) {
return deleteFileWithResponse(fileName, null).flatMap(FluxUtil::toMono);
}
/**
* Deletes the specified file in the directory. If the file doesn't exist the operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFileWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
*
* client.deleteFileWithResponse&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFileWithResponse
*
* @param fileName Name of the file to delete.
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteFileWithResponse(String fileName, DataLakeRequestConditions requestConditions) {
DataLakeFileAsyncClient dataLakeFileAsyncClient;
try {
dataLakeFileAsyncClient = getFileAsyncClient(fileName);
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
return dataLakeFileAsyncClient.deleteWithResponse(requestConditions);
}
/**
* Deletes the specified file in the file system if it exists.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFileIfExists
* <pre>
* client.deleteFileIfExists&
* if &
* System.out.println&
* &
* System.out.println&
* &
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFileIfExists
*
* @param fileName Name of the file to delete.
* @return a reactive response signaling completion. {@code true} indicates that the specified file was successfully
* deleted, {@code false} indicates that the specified file did not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> deleteFileIfExists(String fileName) {
return deleteFileIfExistsWithResponse(fileName, new DataLakePathDeleteOptions())
.map(response -> response.getStatusCode() != 404);
}
/**
* Deletes the specified file in the directory if it exists.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFileIfExistsWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* DataLakePathDeleteOptions options = new DataLakePathDeleteOptions&
* .setRequestConditions&
*
* client.deleteFileIfExistsWithResponse&
* if &
* System.out.println&
* &
* System.out.println&
* &
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteFileIfExistsWithResponse
*
* @param fileName Name of the file to delete.
* @param options {@link DataLakePathDeleteOptions}
* @return A reactive response signaling completion. If {@link Response}'s status code is 200, the specified file was
* successfully deleted. If status code is 404, the specified file does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteFileIfExistsWithResponse(String fileName, DataLakePathDeleteOptions options) {
try {
return withContext(context -> this.deleteFileIfExistsWithResponse(fileName, options, context));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
Mono<Response<Void>> deleteFileIfExistsWithResponse(String fileName, DataLakePathDeleteOptions options,
Context context) {
try {
return getFileAsyncClient(fileName).deleteIfExistsWithResponse(options, context);
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Creates a new DataLakeDirectoryAsyncClient object by concatenating subdirectoryName to the end of
* DataLakeDirectoryAsyncClient's URL. The new DataLakeDirectoryAsyncClient uses the same request policy pipeline
* as the DataLakeDirectoryAsyncClient.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.getSubdirectoryAsyncClient
* <pre>
* DataLakeDirectoryAsyncClient dataLakeDirectoryClient = client.getSubdirectoryAsyncClient&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.getSubdirectoryAsyncClient
*
* @param subdirectoryName A {@code String} representing the name of the sub-directory.
* @return A new {@link DataLakeDirectoryAsyncClient} object which references the directory with the specified name
* in this file system.
*/
public DataLakeDirectoryAsyncClient getSubdirectoryAsyncClient(String subdirectoryName) {
Objects.requireNonNull(subdirectoryName, "'subdirectoryName' can not be set to null");
BlockBlobAsyncClient blockBlobAsyncClient = prepareBuilderAppendPath(subdirectoryName)
.buildBlockBlobAsyncClient();
String pathPrefix = getObjectPath().isEmpty() ? "" : getObjectPath() + "/";
return new DataLakeDirectoryAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(),
getAccountName(), getFileSystemName(),
Utility.urlEncode(pathPrefix + Utility.urlDecode(subdirectoryName)), blockBlobAsyncClient,
this.getSasToken());
}
/**
* Creates a new sub-directory within a directory. By default, this method will not overwrite an existing
* sub-directory. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectory
* <pre>
* DataLakeDirectoryAsyncClient directoryClient = client.createSubdirectory&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectory
*
* @param subdirectoryName Name of the sub-directory to create.
* @return A {@link Mono} containing a {@link DataLakeDirectoryAsyncClient} used to interact with the directory
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeDirectoryAsyncClient> createSubdirectory(String subdirectoryName) {
return createSubdirectory(subdirectoryName, false);
}
/**
* Creates a new sub-directory within a directory. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectory
* <pre>
* boolean overwrite = false; &
* DataLakeDirectoryAsyncClient dClient = client.createSubdirectory&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectory
*
* @param subdirectoryName Name of the sub-directory to create.
* @param overwrite Whether to overwrite, should the subdirectory exist.
* @return A {@link Mono} containing a {@link DataLakeDirectoryAsyncClient} used to interact with the directory
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeDirectoryAsyncClient> createSubdirectory(String subdirectoryName, boolean overwrite) {
DataLakeRequestConditions requestConditions = new DataLakeRequestConditions();
if (!overwrite) {
requestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return createSubdirectoryWithResponse(subdirectoryName, null, null, null, null, requestConditions)
.flatMap(FluxUtil::toMono);
}
/**
* Creates a new sub-directory within a directory. If a sub-directory with the same name already exists, the
* sub-directory will be overwritten. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectoryWithResponse
* <pre>
* PathHttpHeaders httpHeaders = new PathHttpHeaders&
* .setContentLanguage&
* .setContentType&
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* String permissions = "permissions";
* String umask = "umask";
* DataLakeDirectoryAsyncClient newDirectoryClient = client.createSubdirectoryWithResponse&
* directoryName, permissions, umask, httpHeaders, Collections.singletonMap&
* requestConditions
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectoryWithResponse
*
* @param subdirectoryName Name of the sub-directory to create.
* @param permissions POSIX access permissions for the sub-directory owner, the sub-directory owning group, and
* others.
* @param umask Restricts permissions of the sub-directory to be created.
* @param headers {@link PathHttpHeaders}
* @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeDirectoryAsyncClient} used to interact with the sub-directory created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeDirectoryAsyncClient>> createSubdirectoryWithResponse(String subdirectoryName,
String permissions, String umask, PathHttpHeaders headers, Map<String, String> metadata,
DataLakeRequestConditions requestConditions) {
DataLakeDirectoryAsyncClient dataLakeDirectoryAsyncClient;
try {
dataLakeDirectoryAsyncClient = getSubdirectoryAsyncClient(subdirectoryName);
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
return dataLakeDirectoryAsyncClient.createWithResponse(permissions, umask, headers, metadata, requestConditions)
.map(response -> new SimpleResponse<>(response, dataLakeDirectoryAsyncClient));
}
/**
* Creates a new subdirectory within a directory if it does not exist. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectoryIfNotExists
* <pre>
* DataLakeDirectoryAsyncClient subdirectoryClient = client.createSubdirectoryIfNotExists&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectoryIfNotExists
*
* @param subdirectoryName Name of the sub-directory to create.
* @return A {@link Mono} containing a {@link DataLakeDirectoryAsyncClient} used to interact with the subdirectory
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeDirectoryAsyncClient> createSubdirectoryIfNotExists(String subdirectoryName) {
return createSubdirectoryIfNotExistsWithResponse(subdirectoryName, new DataLakePathCreateOptions())
.flatMap(FluxUtil::toMono);
}
/**
* Creates a new sub-directory within a directory if it does not exist. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectoryIfNotExistsWithResponse
* <pre>
* PathHttpHeaders headers = new PathHttpHeaders&
* .setContentLanguage&
* .setContentType&
* String permissions = "permissions";
* String umask = "umask";
* DataLakePathCreateOptions options = new DataLakePathCreateOptions&
* .setPermissions&
*
* client.createSubdirectoryIfNotExistsWithResponse&
* if &
* System.out.println&
* &
* System.out.println&
* &
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.createSubdirectoryIfNotExistsWithResponse
*
* @param subdirectoryName Name of the subdirectory to create.
* @param options {@link DataLakePathCreateOptions}
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link DataLakeDirectoryAsyncClient} used to interact with the subdirectory created. If {@link Response}'s status
* code is 201, a new subdirectory was successfully created. If status code is 409, a subdirectory with the same
* name already existed at this location.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeDirectoryAsyncClient>> createSubdirectoryIfNotExistsWithResponse(
String subdirectoryName, DataLakePathCreateOptions options) {
options = options == null ? new DataLakePathCreateOptions() : options;
options.setRequestConditions(new DataLakeRequestConditions()
.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD));
try {
return createSubdirectoryWithResponse(subdirectoryName, options.getPermissions(), options.getUmask(),
options.getPathHttpHeaders(), options.getMetadata(), options.getRequestConditions())
.onErrorResume(t -> t instanceof DataLakeStorageException && ((DataLakeStorageException) t)
.getStatusCode() == 409,
t -> {
HttpResponse response = ((DataLakeStorageException) t).getResponse();
return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), getSubdirectoryAsyncClient(subdirectoryName)));
});
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Deletes the specified sub-directory in the directory. If the sub-directory doesn't exist or is not empty the
* operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectory
* <pre>
* client.deleteSubdirectory&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectory
*
* @param subdirectoryName Name of the sub-directory to delete.
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteSubdirectory(String subdirectoryName) {
return deleteSubdirectoryWithResponse(subdirectoryName, false, null).flatMap(FluxUtil::toMono);
}
/**
* Deletes the specified sub-directory in the directory. If the sub-directory doesn't exist or is not empty the
* operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectoryWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* boolean recursive = false; &
*
* client.deleteSubdirectoryWithResponse&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectoryWithResponse
*
* @param directoryName Name of the sub-directory to delete.
* @param recursive Whether to delete all paths beneath the sub-directory.
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubdirectoryWithResponse(String directoryName, boolean recursive,
DataLakeRequestConditions requestConditions) {
DataLakeDirectoryAsyncClient dataLakeDirectoryAsyncClient;
try {
dataLakeDirectoryAsyncClient = getSubdirectoryAsyncClient(directoryName);
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
return dataLakeDirectoryAsyncClient.deleteWithResponse(recursive, requestConditions);
}
/**
* Deletes the specified subdirectory in the directory if it exists.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectoryIfExists
* <pre>
* client.deleteSubdirectoryIfExists&
* if &
* System.out.println&
* &
* System.out.println&
* &
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectoryIfExists
*
* @param subdirectoryName Name of the subdirectory to delete.
* @return A reactive response signaling completion. {@code true} indicates that the subdirectory was deleted.
* {@code false} indicates the specified subdirectory does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> deleteSubdirectoryIfExists(String subdirectoryName) {
return deleteSubdirectoryIfExistsWithResponse(subdirectoryName, new DataLakePathDeleteOptions())
.map(response -> response.getStatusCode() != 404);
}
/**
* Deletes the specified subdirectory in the directory if it exists.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectoryIfExistsWithResponse
* <pre>
* DataLakeRequestConditions requestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* boolean recursive = false; &
* DataLakePathDeleteOptions options = new DataLakePathDeleteOptions&
* .setRequestConditions&
*
* client.deleteSubdirectoryIfExistsWithResponse&
* if &
* System.out.println&
* &
* System.out.println&
* &
* &
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.deleteSubdirectoryIfExistsWithResponse
*
* @param directoryName Name of the subdirectory to delete.
* @param options {@link DataLakePathDeleteOptions}
* @return A reactive response signaling completion. If {@link Response}'s status code is 200, the specified subdirectory
* was successfully deleted. If status code is 404, the specified subdirectory does not exist.
*
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubdirectoryIfExistsWithResponse(String directoryName,
DataLakePathDeleteOptions options) {
try {
return deleteSubdirectoryWithResponse(directoryName, options.getIsRecursive(),
options.getRequestConditions())
.onErrorResume(t -> t instanceof DataLakeStorageException
&& ((DataLakeStorageException) t).getStatusCode() == 404,
t -> {
HttpResponse response = ((DataLakeStorageException) t).getResponse();
return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
});
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Moves the directory to another location within the file system.
* For more information see the
* <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.rename
* <pre>
* DataLakeDirectoryAsyncClient renamedClient = client.rename&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.rename
*
* @param destinationFileSystem The file system of the destination within the account.
* {@code null} for the current file system.
* @param destinationPath Relative path from the file system to rename the directory to, excludes the file system
* name. For example if you want to move a directory with fileSystem = "myfilesystem", path = "mydir/mysubdir" to
* another path in myfilesystem (ex: newdir) then set the destinationPath = "newdir"
* @return A {@link Mono} containing a {@link DataLakeDirectoryAsyncClient} used to interact with the new directory
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeDirectoryAsyncClient> rename(String destinationFileSystem, String destinationPath) {
return renameWithResponse(destinationFileSystem, destinationPath, null, null).flatMap(FluxUtil::toMono);
}
/**
* Moves the directory to another location within the file system.
* For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.renameWithResponse
* <pre>
* DataLakeRequestConditions sourceRequestConditions = new DataLakeRequestConditions&
* .setLeaseId&
* DataLakeRequestConditions destinationRequestConditions = new DataLakeRequestConditions&
*
* DataLakeDirectoryAsyncClient newRenamedClient = client.renameWithResponse&
* sourceRequestConditions, destinationRequestConditions&
* System.out.println&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.renameWithResponse
*
* @param destinationFileSystem The file system of the destination within the account.
* {@code null} for the current file system.
* @param destinationPath Relative path from the file system to rename the directory to, excludes the file system
* name. For example if you want to move a directory with fileSystem = "myfilesystem", path = "mydir/mysubdir" to
* another path in myfilesystem (ex: newdir) then set the destinationPath = "newdir"
* @param sourceRequestConditions {@link DataLakeRequestConditions} against the source.
* @param destinationRequestConditions {@link DataLakeRequestConditions} against the destination.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeDirectoryAsyncClient} used to interact with the directory created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeDirectoryAsyncClient>> renameWithResponse(String destinationFileSystem,
String destinationPath, DataLakeRequestConditions sourceRequestConditions,
DataLakeRequestConditions destinationRequestConditions) {
try {
return withContext(context -> renameWithResponse(destinationFileSystem, destinationPath,
sourceRequestConditions, destinationRequestConditions, context)).map(
response -> new SimpleResponse<>(response, new DataLakeDirectoryAsyncClient(response.getValue())));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Returns a reactive Publisher emitting all the files/directories in this directory lazily as needed. For more
* information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.listPaths -->
* <pre>
* client.listPaths&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.listPaths -->
*
* @return A reactive response emitting the list of files/directories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<PathItem> listPaths() {
return this.listPaths(false, false, null);
}
/**
* Returns a reactive Publisher emitting all the files/directories in this directory lazily as needed. For more
* information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.listPaths
* <pre>
* client.listPaths&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.file.datalake.DataLakeDirectoryAsyncClient.listPaths
*
* @param recursive Specifies if the call should recursively include all paths.
* @param userPrincipleNameReturned If "true", the user identity values returned by the x-ms-owner, x-ms-group,
* and x-ms-acl response headers will be transformed from Azure Active Directory Object IDs to User Principal Names.
* If "false", the values will be returned as Azure Active Directory Object IDs.
* The default value is false. Note that group and application Object IDs are not translated because they do not
* have unique friendly names.
* @param maxResults Specifies the maximum number of blobs to return per page, including all BlobPrefix elements. If
* the request does not specify maxResults or specifies a value greater than 5,000, the server will return up to
* 5,000 items per page.
* @return A reactive response emitting the list of files/directories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<PathItem> listPaths(boolean recursive, boolean userPrincipleNameReturned, Integer maxResults) {
try {
return listPathsWithOptionalTimeout(recursive, userPrincipleNameReturned, maxResults, null);
} catch (RuntimeException ex) {
return pagedFluxError(LOGGER, ex);
}
}
PagedFlux<PathItem> listPathsWithOptionalTimeout(boolean recursive, boolean userPrincipleNameReturned,
Integer maxResults, Duration timeout) {
BiFunction<String, Integer, Mono<PagedResponse<PathItem>>> func =
(marker, pageSize) -> listPathsSegment(marker, recursive, userPrincipleNameReturned,
pageSize == null ? maxResults : pageSize, timeout)
.map(response -> {
List<PathItem> value = response.getValue() == null
? Collections.emptyList()
: response.getValue().getPaths().stream()
.map(Transforms::toPathItem)
.collect(Collectors.toList());
return new PagedResponseBase<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
value,
response.getDeserializedHeaders().getXMsContinuation(),
response.getDeserializedHeaders());
});
return new PagedFlux<>(pageSize -> func.apply(null, pageSize), func);
}
private Mono<FileSystemsListPathsResponse> listPathsSegment(String marker, boolean recursive,
boolean userPrincipleNameReturned, Integer maxResults, Duration timeout) {
return StorageImplUtils.applyOptionalTimeout(
this.fileSystemDataLakeStorage.getFileSystems().listPathsWithResponseAsync(
recursive, null, null, marker, getDirectoryPath(), maxResults, userPrincipleNameReturned,
Context.NONE), timeout);
}
/**
* Prepares a SpecializedBlobClientBuilder with the pathname appended to the end of the current BlockBlobClient's
* url
* @param pathName The name of the path to append
* @return {@link SpecializedBlobClientBuilder}
*/
SpecializedBlobClientBuilder prepareBuilderAppendPath(String pathName) {
String blobUrl = DataLakeImplUtils.endpointToDesiredEndpoint(getPathUrl(), "blob", "dfs");
return new SpecializedBlobClientBuilder()
.pipeline(getHttpPipeline())
.serviceVersion(TransformUtils.toBlobServiceVersion(getServiceVersion()))
.endpoint(StorageImplUtils.appendToUrlPath(blobUrl, pathName).toString());
}
} |
- we should rename `t` to `e` - another improvement. If `t` is already `RuntimeException` we don't have to wrap it. Perhaps we need another method in the logger and encapsulate it there. | private int getJavaVersion() {
String version = System.getProperty("java.version");
if (CoreUtils.isNullOrEmpty(version)) {
throw LOGGER.logExceptionAsError(new RuntimeException("Can't find 'java.version' system property."));
}
if (version.startsWith("1.")) {
if (version.length() < 3) {
throw LOGGER.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version));
}
try {
return Integer.parseInt(version.substring(2, 3));
} catch (Exception t) {
throw LOGGER.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version, t));
}
} else {
int idx = version.indexOf(".");
if (idx == -1) {
return Integer.parseInt(version);
}
try {
return Integer.parseInt(version.substring(0, idx));
} catch (Exception t) {
throw LOGGER.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version, t));
}
}
} | throw LOGGER.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version, t)); | private int getJavaVersion() {
String version = System.getProperty("java.version");
if (CoreUtils.isNullOrEmpty(version)) {
throw LOGGER.logExceptionAsError(new RuntimeException("Can't find 'java.version' system property."));
}
if (version.startsWith("1.")) {
if (version.length() < 3) {
throw LOGGER.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version));
}
try {
return Integer.parseInt(version.substring(2, 3));
} catch (Exception t) {
throw LOGGER.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version, t));
}
} else {
int idx = version.indexOf(".");
if (idx == -1) {
return Integer.parseInt(version);
}
try {
return Integer.parseInt(version.substring(0, idx));
} catch (Exception t) {
throw LOGGER.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version, t));
}
}
} | class JdkAsyncHttpClient implements HttpClient {
private static final ClientLogger LOGGER = new ClientLogger(JdkAsyncHttpClient.class);
private final java.net.http.HttpClient jdkHttpClient;
private final Set<String> restrictedHeaders;
JdkAsyncHttpClient(java.net.http.HttpClient httpClient, Set<String> restrictedHeaders) {
this.jdkHttpClient = httpClient;
int javaVersion = getJavaVersion();
if (javaVersion <= 11) {
throw LOGGER.logExceptionAsError(
new UnsupportedOperationException("JdkAsyncHttpClient is not supported in Java version 11 and below."));
}
this.restrictedHeaders = restrictedHeaders;
LOGGER.verbose("Effective restricted headers: {}", restrictedHeaders);
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Context.NONE);
}
@Override
public Mono<HttpResponse> send(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
return toJdkHttpRequest(request)
.flatMap(jdkRequest -> Mono.fromCompletionStage(jdkHttpClient.sendAsync(jdkRequest, ofPublisher()))
.flatMap(innerResponse -> {
if (eagerlyReadResponse) {
int statusCode = innerResponse.statusCode();
HttpHeaders headers = fromJdkHttpHeaders(innerResponse.headers());
return FluxUtil.collectBytesFromNetworkResponse(JdkFlowAdapter
.flowPublisherToFlux(innerResponse.body())
.flatMapSequential(Flux::fromIterable), headers)
.map(bytes -> new BufferedJdkHttpResponse(request, statusCode, headers, bytes));
} else {
return Mono.just(new JdkHttpResponse(request, innerResponse));
}
}));
}
/**
* Converts the given azure-core request to the JDK HttpRequest type.
*
* @param request the azure-core request
* @return the Mono emitting HttpRequest
*/
private Mono<java.net.http.HttpRequest> toJdkHttpRequest(HttpRequest request) {
return Mono.fromCallable(() -> {
final java.net.http.HttpRequest.Builder builder = java.net.http.HttpRequest.newBuilder();
try {
builder.uri(request.getUrl().toURI());
} catch (URISyntaxException e) {
throw LOGGER.logExceptionAsError(Exceptions.propagate(e));
}
final HttpHeaders headers = request.getHeaders();
if (headers != null) {
for (HttpHeader header : headers) {
final String headerName = header.getName();
if (!restrictedHeaders.contains(headerName)) {
header.getValuesList().forEach(headerValue -> builder.header(headerName, headerValue));
} else {
LOGGER.warning("The header '" + headerName + "' is restricted by default in JDK HttpClient 12 "
+ "and above. This header can be added to allow list in JAVA_HOME/conf/net.properties "
+ "or in System.setProperty() or in Configuration. Use the key 'jdk.httpclient"
+ ".allowRestrictedHeaders' and a comma separated list of header names.");
}
}
}
switch (request.getHttpMethod()) {
case GET:
return builder.GET().build();
case HEAD:
return builder.method("HEAD", noBody()).build();
default:
final String contentLength = request.getHeaders().getValue("content-length");
final BodyPublisher bodyPublisher = toBodyPublisher(request.getBody(), contentLength);
return builder.method(request.getHttpMethod().toString(), bodyPublisher).build();
}
});
}
/**
* Create BodyPublisher from the given java.nio.ByteBuffer publisher.
*
* @param bbPublisher stream of java.nio.ByteBuffer representing request content
* @return the request BodyPublisher
*/
private static BodyPublisher toBodyPublisher(Flux<ByteBuffer> bbPublisher, String contentLength) {
if (bbPublisher == null) {
return noBody();
}
final Flow.Publisher<ByteBuffer> bbFlowPublisher = JdkFlowAdapter.publisherToFlowPublisher(bbPublisher);
if (CoreUtils.isNullOrEmpty(contentLength)) {
return fromPublisher(bbFlowPublisher);
} else {
long contentLengthLong = Long.parseLong(contentLength);
if (contentLengthLong < 1) {
return noBody();
} else {
return fromPublisher(bbFlowPublisher, contentLengthLong);
}
}
}
/**
* Get the java runtime major version.
*
* @return the java major version
*/
/**
* Converts the given JDK Http headers to azure-core Http header.
*
* @param headers the JDK Http headers
* @return the azure-core Http headers
*/
static HttpHeaders fromJdkHttpHeaders(java.net.http.HttpHeaders headers) {
final HttpHeaders httpHeaders = new HttpHeaders();
for (Map.Entry<String, List<String>> kvp : headers.map().entrySet()) {
if (CoreUtils.isNullOrEmpty(kvp.getValue())) {
continue;
}
httpHeaders.set(kvp.getKey(), kvp.getValue());
}
return httpHeaders;
}
} | class JdkAsyncHttpClient implements HttpClient {
private static final ClientLogger LOGGER = new ClientLogger(JdkAsyncHttpClient.class);
private final java.net.http.HttpClient jdkHttpClient;
private final Set<String> restrictedHeaders;
JdkAsyncHttpClient(java.net.http.HttpClient httpClient, Set<String> restrictedHeaders) {
this.jdkHttpClient = httpClient;
int javaVersion = getJavaVersion();
if (javaVersion <= 11) {
throw LOGGER.logExceptionAsError(
new UnsupportedOperationException("JdkAsyncHttpClient is not supported in Java version 11 and below."));
}
this.restrictedHeaders = restrictedHeaders;
LOGGER.verbose("Effective restricted headers: {}", restrictedHeaders);
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Context.NONE);
}
@Override
public Mono<HttpResponse> send(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
return toJdkHttpRequest(request)
.flatMap(jdkRequest -> Mono.fromCompletionStage(jdkHttpClient.sendAsync(jdkRequest, ofPublisher()))
.flatMap(innerResponse -> {
if (eagerlyReadResponse) {
int statusCode = innerResponse.statusCode();
HttpHeaders headers = fromJdkHttpHeaders(innerResponse.headers());
return FluxUtil.collectBytesFromNetworkResponse(JdkFlowAdapter
.flowPublisherToFlux(innerResponse.body())
.flatMapSequential(Flux::fromIterable), headers)
.map(bytes -> new BufferedJdkHttpResponse(request, statusCode, headers, bytes));
} else {
return Mono.just(new JdkHttpResponse(request, innerResponse));
}
}));
}
/**
* Converts the given azure-core request to the JDK HttpRequest type.
*
* @param request the azure-core request
* @return the Mono emitting HttpRequest
*/
private Mono<java.net.http.HttpRequest> toJdkHttpRequest(HttpRequest request) {
return Mono.fromCallable(() -> {
final java.net.http.HttpRequest.Builder builder = java.net.http.HttpRequest.newBuilder();
try {
builder.uri(request.getUrl().toURI());
} catch (URISyntaxException e) {
throw LOGGER.logExceptionAsError(Exceptions.propagate(e));
}
final HttpHeaders headers = request.getHeaders();
if (headers != null) {
for (HttpHeader header : headers) {
final String headerName = header.getName();
if (!restrictedHeaders.contains(headerName)) {
header.getValuesList().forEach(headerValue -> builder.header(headerName, headerValue));
} else {
LOGGER.warning("The header '" + headerName + "' is restricted by default in JDK HttpClient 12 "
+ "and above. This header can be added to allow list in JAVA_HOME/conf/net.properties "
+ "or in System.setProperty() or in Configuration. Use the key 'jdk.httpclient"
+ ".allowRestrictedHeaders' and a comma separated list of header names.");
}
}
}
switch (request.getHttpMethod()) {
case GET:
return builder.GET().build();
case HEAD:
return builder.method("HEAD", noBody()).build();
default:
final String contentLength = request.getHeaders().getValue("content-length");
final BodyPublisher bodyPublisher = toBodyPublisher(request.getBody(), contentLength);
return builder.method(request.getHttpMethod().toString(), bodyPublisher).build();
}
});
}
/**
* Create BodyPublisher from the given java.nio.ByteBuffer publisher.
*
* @param bbPublisher stream of java.nio.ByteBuffer representing request content
* @return the request BodyPublisher
*/
private static BodyPublisher toBodyPublisher(Flux<ByteBuffer> bbPublisher, String contentLength) {
if (bbPublisher == null) {
return noBody();
}
final Flow.Publisher<ByteBuffer> bbFlowPublisher = JdkFlowAdapter.publisherToFlowPublisher(bbPublisher);
if (CoreUtils.isNullOrEmpty(contentLength)) {
return fromPublisher(bbFlowPublisher);
} else {
long contentLengthLong = Long.parseLong(contentLength);
if (contentLengthLong < 1) {
return noBody();
} else {
return fromPublisher(bbFlowPublisher, contentLengthLong);
}
}
}
/**
* Get the java runtime major version.
*
* @return the java major version
*/
/**
* Converts the given JDK Http headers to azure-core Http header.
*
* @param headers the JDK Http headers
* @return the azure-core Http headers
*/
static HttpHeaders fromJdkHttpHeaders(java.net.http.HttpHeaders headers) {
final HttpHeaders httpHeaders = new HttpHeaders();
for (Map.Entry<String, List<String>> kvp : headers.map().entrySet()) {
if (CoreUtils.isNullOrEmpty(kvp.getValue())) {
continue;
}
httpHeaders.set(kvp.getKey(), kvp.getValue());
}
return httpHeaders;
}
} |
Yeah, I think there are a lot of cases where we end up wrapping an exception type in the type itself. I agree, we should look into offering a convenience method for this. | private int getJavaVersion() {
String version = System.getProperty("java.version");
if (CoreUtils.isNullOrEmpty(version)) {
throw LOGGER.logExceptionAsError(new RuntimeException("Can't find 'java.version' system property."));
}
if (version.startsWith("1.")) {
if (version.length() < 3) {
throw LOGGER.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version));
}
try {
return Integer.parseInt(version.substring(2, 3));
} catch (Exception t) {
throw LOGGER.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version, t));
}
} else {
int idx = version.indexOf(".");
if (idx == -1) {
return Integer.parseInt(version);
}
try {
return Integer.parseInt(version.substring(0, idx));
} catch (Exception t) {
throw LOGGER.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version, t));
}
}
} | throw LOGGER.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version, t)); | private int getJavaVersion() {
String version = System.getProperty("java.version");
if (CoreUtils.isNullOrEmpty(version)) {
throw LOGGER.logExceptionAsError(new RuntimeException("Can't find 'java.version' system property."));
}
if (version.startsWith("1.")) {
if (version.length() < 3) {
throw LOGGER.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version));
}
try {
return Integer.parseInt(version.substring(2, 3));
} catch (Exception t) {
throw LOGGER.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version, t));
}
} else {
int idx = version.indexOf(".");
if (idx == -1) {
return Integer.parseInt(version);
}
try {
return Integer.parseInt(version.substring(0, idx));
} catch (Exception t) {
throw LOGGER.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version, t));
}
}
} | class JdkAsyncHttpClient implements HttpClient {
private static final ClientLogger LOGGER = new ClientLogger(JdkAsyncHttpClient.class);
private final java.net.http.HttpClient jdkHttpClient;
private final Set<String> restrictedHeaders;
JdkAsyncHttpClient(java.net.http.HttpClient httpClient, Set<String> restrictedHeaders) {
this.jdkHttpClient = httpClient;
int javaVersion = getJavaVersion();
if (javaVersion <= 11) {
throw LOGGER.logExceptionAsError(
new UnsupportedOperationException("JdkAsyncHttpClient is not supported in Java version 11 and below."));
}
this.restrictedHeaders = restrictedHeaders;
LOGGER.verbose("Effective restricted headers: {}", restrictedHeaders);
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Context.NONE);
}
@Override
public Mono<HttpResponse> send(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
return toJdkHttpRequest(request)
.flatMap(jdkRequest -> Mono.fromCompletionStage(jdkHttpClient.sendAsync(jdkRequest, ofPublisher()))
.flatMap(innerResponse -> {
if (eagerlyReadResponse) {
int statusCode = innerResponse.statusCode();
HttpHeaders headers = fromJdkHttpHeaders(innerResponse.headers());
return FluxUtil.collectBytesFromNetworkResponse(JdkFlowAdapter
.flowPublisherToFlux(innerResponse.body())
.flatMapSequential(Flux::fromIterable), headers)
.map(bytes -> new BufferedJdkHttpResponse(request, statusCode, headers, bytes));
} else {
return Mono.just(new JdkHttpResponse(request, innerResponse));
}
}));
}
/**
* Converts the given azure-core request to the JDK HttpRequest type.
*
* @param request the azure-core request
* @return the Mono emitting HttpRequest
*/
private Mono<java.net.http.HttpRequest> toJdkHttpRequest(HttpRequest request) {
return Mono.fromCallable(() -> {
final java.net.http.HttpRequest.Builder builder = java.net.http.HttpRequest.newBuilder();
try {
builder.uri(request.getUrl().toURI());
} catch (URISyntaxException e) {
throw LOGGER.logExceptionAsError(Exceptions.propagate(e));
}
final HttpHeaders headers = request.getHeaders();
if (headers != null) {
for (HttpHeader header : headers) {
final String headerName = header.getName();
if (!restrictedHeaders.contains(headerName)) {
header.getValuesList().forEach(headerValue -> builder.header(headerName, headerValue));
} else {
LOGGER.warning("The header '" + headerName + "' is restricted by default in JDK HttpClient 12 "
+ "and above. This header can be added to allow list in JAVA_HOME/conf/net.properties "
+ "or in System.setProperty() or in Configuration. Use the key 'jdk.httpclient"
+ ".allowRestrictedHeaders' and a comma separated list of header names.");
}
}
}
switch (request.getHttpMethod()) {
case GET:
return builder.GET().build();
case HEAD:
return builder.method("HEAD", noBody()).build();
default:
final String contentLength = request.getHeaders().getValue("content-length");
final BodyPublisher bodyPublisher = toBodyPublisher(request.getBody(), contentLength);
return builder.method(request.getHttpMethod().toString(), bodyPublisher).build();
}
});
}
/**
* Create BodyPublisher from the given java.nio.ByteBuffer publisher.
*
* @param bbPublisher stream of java.nio.ByteBuffer representing request content
* @return the request BodyPublisher
*/
private static BodyPublisher toBodyPublisher(Flux<ByteBuffer> bbPublisher, String contentLength) {
if (bbPublisher == null) {
return noBody();
}
final Flow.Publisher<ByteBuffer> bbFlowPublisher = JdkFlowAdapter.publisherToFlowPublisher(bbPublisher);
if (CoreUtils.isNullOrEmpty(contentLength)) {
return fromPublisher(bbFlowPublisher);
} else {
long contentLengthLong = Long.parseLong(contentLength);
if (contentLengthLong < 1) {
return noBody();
} else {
return fromPublisher(bbFlowPublisher, contentLengthLong);
}
}
}
/**
* Get the java runtime major version.
*
* @return the java major version
*/
/**
* Converts the given JDK Http headers to azure-core Http header.
*
* @param headers the JDK Http headers
* @return the azure-core Http headers
*/
static HttpHeaders fromJdkHttpHeaders(java.net.http.HttpHeaders headers) {
final HttpHeaders httpHeaders = new HttpHeaders();
for (Map.Entry<String, List<String>> kvp : headers.map().entrySet()) {
if (CoreUtils.isNullOrEmpty(kvp.getValue())) {
continue;
}
httpHeaders.set(kvp.getKey(), kvp.getValue());
}
return httpHeaders;
}
} | class JdkAsyncHttpClient implements HttpClient {
private static final ClientLogger LOGGER = new ClientLogger(JdkAsyncHttpClient.class);
private final java.net.http.HttpClient jdkHttpClient;
private final Set<String> restrictedHeaders;
JdkAsyncHttpClient(java.net.http.HttpClient httpClient, Set<String> restrictedHeaders) {
this.jdkHttpClient = httpClient;
int javaVersion = getJavaVersion();
if (javaVersion <= 11) {
throw LOGGER.logExceptionAsError(
new UnsupportedOperationException("JdkAsyncHttpClient is not supported in Java version 11 and below."));
}
this.restrictedHeaders = restrictedHeaders;
LOGGER.verbose("Effective restricted headers: {}", restrictedHeaders);
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Context.NONE);
}
@Override
public Mono<HttpResponse> send(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
return toJdkHttpRequest(request)
.flatMap(jdkRequest -> Mono.fromCompletionStage(jdkHttpClient.sendAsync(jdkRequest, ofPublisher()))
.flatMap(innerResponse -> {
if (eagerlyReadResponse) {
int statusCode = innerResponse.statusCode();
HttpHeaders headers = fromJdkHttpHeaders(innerResponse.headers());
return FluxUtil.collectBytesFromNetworkResponse(JdkFlowAdapter
.flowPublisherToFlux(innerResponse.body())
.flatMapSequential(Flux::fromIterable), headers)
.map(bytes -> new BufferedJdkHttpResponse(request, statusCode, headers, bytes));
} else {
return Mono.just(new JdkHttpResponse(request, innerResponse));
}
}));
}
/**
* Converts the given azure-core request to the JDK HttpRequest type.
*
* @param request the azure-core request
* @return the Mono emitting HttpRequest
*/
private Mono<java.net.http.HttpRequest> toJdkHttpRequest(HttpRequest request) {
return Mono.fromCallable(() -> {
final java.net.http.HttpRequest.Builder builder = java.net.http.HttpRequest.newBuilder();
try {
builder.uri(request.getUrl().toURI());
} catch (URISyntaxException e) {
throw LOGGER.logExceptionAsError(Exceptions.propagate(e));
}
final HttpHeaders headers = request.getHeaders();
if (headers != null) {
for (HttpHeader header : headers) {
final String headerName = header.getName();
if (!restrictedHeaders.contains(headerName)) {
header.getValuesList().forEach(headerValue -> builder.header(headerName, headerValue));
} else {
LOGGER.warning("The header '" + headerName + "' is restricted by default in JDK HttpClient 12 "
+ "and above. This header can be added to allow list in JAVA_HOME/conf/net.properties "
+ "or in System.setProperty() or in Configuration. Use the key 'jdk.httpclient"
+ ".allowRestrictedHeaders' and a comma separated list of header names.");
}
}
}
switch (request.getHttpMethod()) {
case GET:
return builder.GET().build();
case HEAD:
return builder.method("HEAD", noBody()).build();
default:
final String contentLength = request.getHeaders().getValue("content-length");
final BodyPublisher bodyPublisher = toBodyPublisher(request.getBody(), contentLength);
return builder.method(request.getHttpMethod().toString(), bodyPublisher).build();
}
});
}
/**
* Create BodyPublisher from the given java.nio.ByteBuffer publisher.
*
* @param bbPublisher stream of java.nio.ByteBuffer representing request content
* @return the request BodyPublisher
*/
private static BodyPublisher toBodyPublisher(Flux<ByteBuffer> bbPublisher, String contentLength) {
if (bbPublisher == null) {
return noBody();
}
final Flow.Publisher<ByteBuffer> bbFlowPublisher = JdkFlowAdapter.publisherToFlowPublisher(bbPublisher);
if (CoreUtils.isNullOrEmpty(contentLength)) {
return fromPublisher(bbFlowPublisher);
} else {
long contentLengthLong = Long.parseLong(contentLength);
if (contentLengthLong < 1) {
return noBody();
} else {
return fromPublisher(bbFlowPublisher, contentLengthLong);
}
}
}
/**
* Get the java runtime major version.
*
* @return the java major version
*/
/**
* Converts the given JDK Http headers to azure-core Http header.
*
* @param headers the JDK Http headers
* @return the azure-core Http headers
*/
static HttpHeaders fromJdkHttpHeaders(java.net.http.HttpHeaders headers) {
final HttpHeaders httpHeaders = new HttpHeaders();
for (Map.Entry<String, List<String>> kvp : headers.map().entrySet()) {
if (CoreUtils.isNullOrEmpty(kvp.getValue())) {
continue;
}
httpHeaders.set(kvp.getKey(), kvp.getValue());
}
return httpHeaders;
}
} |
Should this not be monoError instead so we also log the exception? | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl());
if (overwrite || urlBuilder.getPort() == null) {
LOGGER.log(LogLevel.VERBOSE, () -> "Changing port to " + port);
try {
context.getHttpRequest().setUrl(urlBuilder.setPort(port).toUrl());
} catch (MalformedURLException e) {
return Mono.error(new RuntimeException("Failed to set the HTTP request port to " + port + ".", e));
}
}
return next.process();
} | return Mono.error(new RuntimeException("Failed to set the HTTP request port to " + port + ".", e)); | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl());
if (overwrite || urlBuilder.getPort() == null) {
LOGGER.log(LogLevel.VERBOSE, () -> "Changing port to " + port);
try {
context.getHttpRequest().setUrl(urlBuilder.setPort(port).toUrl());
} catch (MalformedURLException e) {
return Mono.error(new RuntimeException("Failed to set the HTTP request port to " + port + ".", e));
}
}
return next.process();
} | class PortPolicy implements HttpPipelinePolicy {
private static final ClientLogger LOGGER = new ClientLogger(PortPolicy.class);
private final int port;
private final boolean overwrite;
/**
* Creates a new PortPolicy object.
*
* @param port The port to set.
* @param overwrite Whether to overwrite a {@link HttpRequest HttpRequest's} port if it already has one.
*/
public PortPolicy(int port, boolean overwrite) {
this.port = port;
this.overwrite = overwrite;
}
@Override
} | class PortPolicy implements HttpPipelinePolicy {
private static final ClientLogger LOGGER = new ClientLogger(PortPolicy.class);
private final int port;
private final boolean overwrite;
/**
* Creates a new PortPolicy object.
*
* @param port The port to set.
* @param overwrite Whether to overwrite a {@link HttpRequest HttpRequest's} port if it already has one.
*/
public PortPolicy(int port, boolean overwrite) {
this.port = port;
this.overwrite = overwrite;
}
@Override
} |
Is `completeEmitter1` `null`? How does `getCompleteEmitter()) == null` work in `SynchronousMessageSubscriber`? What is the purpose of these mock? | public void setup() {
mocksCloseable = MockitoAnnotations.openMocks(this);
when(work1.getId()).thenReturn(WORK_ID);
when(work1.getNumberOfEvents()).thenReturn(NUMBER_OF_WORK_ITEMS);
completeEmitter1 = Sinks.empty();
when(work1.getCompleteEmitter()).thenReturn(completeEmitter1);
when(work2.getId()).thenReturn(WORK_ID_2);
when(work2.getNumberOfEvents()).thenReturn(NUMBER_OF_WORK_ITEMS_2);
completeEmitter2 = Sinks.empty();
when(work2.getCompleteEmitter()).thenReturn(completeEmitter2);
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, false, operationTimeout);
} | when(work1.getCompleteEmitter()).thenReturn(completeEmitter1); | public void setup() {
mocksCloseable = MockitoAnnotations.openMocks(this);
when(work1.getId()).thenReturn(WORK_ID);
when(work1.getNumberOfEvents()).thenReturn(NUMBER_OF_WORK_ITEMS);
when(work2.getId()).thenReturn(WORK_ID_2);
when(work2.getNumberOfEvents()).thenReturn(NUMBER_OF_WORK_ITEMS_2);
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, false, operationTimeout);
} | class SynchronousMessageSubscriberTest {
private static final long WORK_ID = 10L;
private static final long WORK_ID_2 = 10L;
private static final int NUMBER_OF_WORK_ITEMS = 4;
private static final int NUMBER_OF_WORK_ITEMS_2 = 3;
private final Duration operationTimeout = Duration.ofSeconds(10);
@Mock
private ServiceBusReceiverAsyncClient asyncClient;
@Mock
private SynchronousReceiveWork work1;
@Mock
private SynchronousReceiveWork work2;
@Mock
private Subscription subscription;
@Captor
private ArgumentCaptor<Long> subscriptionArgumentCaptor;
private SynchronousMessageSubscriber syncSubscriber;
private AutoCloseable mocksCloseable;
private Sinks.Empty<Void> completeEmitter1;
private Sinks.Empty<Void> completeEmitter2;
@BeforeEach
@AfterEach
public void teardown() throws Exception {
if (mocksCloseable != null) {
mocksCloseable.close();
}
syncSubscriber.dispose();
Mockito.framework().clearInlineMock(this);
}
/**
* Verify that the initial subscription requests work1's number of work items.
*/
@Test
public void workAddedAndRequestedUpstream() {
when(work1.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS);
syncSubscriber.hookOnSubscribe(subscription);
verify(subscription).request(work1.getNumberOfEvents());
verify(work1).start();
assertEquals(0, syncSubscriber.getWorkQueueSize());
}
/**
* A work gets queued in work queue.
*/
@Test
public void queueWorkTest() {
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, false, operationTimeout);
syncSubscriber.queueWork(work2);
assertEquals(2, syncSubscriber.getWorkQueueSize());
}
/**
* Verifies that this processes multiple work items.
*/
@Test
public void processesMultipleWorkItems() {
final SynchronousReceiveWork work3 = mock(SynchronousReceiveWork.class);
when(work3.getId()).thenReturn(3L);
when(work3.getNumberOfEvents()).thenReturn(1);
when(work3.getCompleteEmitter()).thenReturn(Sinks.empty());
final ServiceBusReceivedMessage message1 = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message2 = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message3 = mock(ServiceBusReceivedMessage.class);
final AtomicBoolean isTerminal = new AtomicBoolean(false);
final AtomicInteger remaining = new AtomicInteger(NUMBER_OF_WORK_ITEMS);
doAnswer(invocation -> {
ServiceBusReceivedMessage arg = invocation.getArgument(0);
if (arg == message1 || arg == message2) {
remaining.decrementAndGet();
return true;
} else {
return false;
}
}).when(work1).emitNext(any(ServiceBusReceivedMessage.class));
doAnswer(invocation -> isTerminal.get()).when(work1).isTerminal();
doAnswer(invocation -> remaining.get()).when(work1).getRemainingEvents();
when(work2.emitNext(message3)).thenReturn(true);
when(work2.isTerminal()).thenReturn(false);
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, false, operationTimeout);
syncSubscriber.queueWork(work2);
syncSubscriber.queueWork(work3);
syncSubscriber.hookOnSubscribe(subscription);
assertEquals(2, syncSubscriber.getWorkQueueSize());
syncSubscriber.hookOnNext(message1);
syncSubscriber.hookOnNext(message2);
isTerminal.set(true);
syncSubscriber.hookOnNext(message3);
verify(work2).start();
verify(work2).emitNext(message3);
assertEquals(1, syncSubscriber.getWorkQueueSize());
verify(subscription, times(2)).request(subscriptionArgumentCaptor.capture());
final List<Long> allRequests = subscriptionArgumentCaptor.getAllValues();
final Set<Long> expected = new HashSet<>();
expected.add((long) work1.getNumberOfEvents());
final long requestedAfterWork1 = NUMBER_OF_WORK_ITEMS - remaining.get();
final long expectedDifference = work2.getNumberOfEvents() - requestedAfterWork1;
expected.add(expectedDifference);
assertEquals(expected.size(), allRequests.size());
allRequests.forEach(r -> assertTrue(expected.contains(r)));
}
/**
* Verifies that when previous work have completed, update current work
*/
@Test
public void updateCurrentWorkWhenQueueIsNotEmpty() {
final SynchronousReceiveWork work3 = mock(SynchronousReceiveWork.class);
when(work3.getId()).thenReturn(3L);
when(work3.getNumberOfEvents()).thenReturn(1);
when(work3.getCompleteEmitter()).thenReturn(Sinks.empty());
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, false, operationTimeout);
syncSubscriber.queueWork(work2);
syncSubscriber.queueWork(work3);
assertEquals(3, syncSubscriber.getWorkQueueSize());
syncSubscriber.hookOnSubscribe(subscription);
assertEquals(2, syncSubscriber.getWorkQueueSize());
when(work1.isTerminal()).thenReturn(true);
completeEmitter1.emitEmpty(Sinks.EmitFailureHandler.FAIL_FAST);
verify(work2).start();
assertEquals(1, syncSubscriber.getWorkQueueSize());
when(work2.isTerminal()).thenReturn(true);
completeEmitter2.emitEmpty(Sinks.EmitFailureHandler.FAIL_FAST);
verify(work3).start();
assertEquals(0, syncSubscriber.getWorkQueueSize());
}
/**
* Verifies that all work items are completed if the subscriber is disposed.
*/
@Test
public void completesWorkOnCancel() {
when(work1.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS);
when(work2.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS_2);
syncSubscriber.queueWork(work2);
syncSubscriber.hookOnSubscribe(subscription);
syncSubscriber.hookOnCancel();
verify(work1).complete(any(String.class), isNull());
verify(work2).complete(any(String.class), isNull());
assertEquals(0, syncSubscriber.getWorkQueueSize());
}
/**
* Verifies that all work items are completed if the subscriber encounters an error.
*/
@Test
public void completesWorkOnError() {
final Throwable error = new AmqpException(false, "Test-error", new AmqpErrorContext("foo.com"));
when(work1.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS);
when(work2.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS_2);
syncSubscriber.queueWork(work2);
syncSubscriber.hookOnSubscribe(subscription);
syncSubscriber.hookOnError(error);
verify(work1).complete(any(String.class), eq(error));
verify(work2).complete(any(String.class), eq(error));
assertEquals(0, syncSubscriber.getWorkQueueSize());
}
@Test
public void releaseIfNoActiveReceive() {
when(work1.emitNext(any(ServiceBusReceivedMessage.class))).thenReturn(true);
final ServiceBusReceivedMessage message1beforeTimeout = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message2beforeTimeout = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message1afterTimeout = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message2afterTimeout = mock(ServiceBusReceivedMessage.class);
final AtomicBoolean isTerminal = new AtomicBoolean(false);
doAnswer(invocation -> isTerminal.get()).when(work1).isTerminal();
final AtomicInteger expectedReleaseCalls = new AtomicInteger(0);
final AtomicBoolean hadUnexpectedReleaseCall = new AtomicBoolean(false);
doAnswer(invocation -> {
ServiceBusReceivedMessage arg = invocation.getArgument(0);
if (arg == message1afterTimeout || arg == message2afterTimeout) {
expectedReleaseCalls.incrementAndGet();
} else {
hadUnexpectedReleaseCall.set(true);
}
return Mono.empty();
}).when(asyncClient).release(any(ServiceBusReceivedMessage.class));
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, true, operationTimeout);
syncSubscriber.hookOnSubscribe(subscription);
syncSubscriber.hookOnNext(message1beforeTimeout);
syncSubscriber.hookOnNext(message2beforeTimeout);
isTerminal.set(true);
syncSubscriber.hookOnNext(message1afterTimeout);
syncSubscriber.hookOnNext(message2afterTimeout);
verify(work1).emitNext(message1beforeTimeout);
verify(work1).emitNext(message2beforeTimeout);
verify(work1, never()).emitNext(message1afterTimeout);
verify(work1, never()).emitNext(message2afterTimeout);
assertEquals(2, expectedReleaseCalls.get());
assertFalse(hadUnexpectedReleaseCall.get());
}
} | class SynchronousMessageSubscriberTest {
private static final long WORK_ID = 10L;
private static final long WORK_ID_2 = 10L;
private static final int NUMBER_OF_WORK_ITEMS = 4;
private static final int NUMBER_OF_WORK_ITEMS_2 = 3;
private final Duration operationTimeout = Duration.ofSeconds(10);
@Mock
private ServiceBusReceiverAsyncClient asyncClient;
@Mock
private SynchronousReceiveWork work1;
@Mock
private SynchronousReceiveWork work2;
@Mock
private Subscription subscription;
@Captor
private ArgumentCaptor<Long> subscriptionArgumentCaptor;
private SynchronousMessageSubscriber syncSubscriber;
private AutoCloseable mocksCloseable;
@BeforeEach
@AfterEach
public void teardown() throws Exception {
if (mocksCloseable != null) {
mocksCloseable.close();
}
syncSubscriber.dispose();
Mockito.framework().clearInlineMock(this);
}
/**
* Verify that the initial subscription requests work1's number of work items.
*/
@Test
public void workAddedAndRequestedUpstream() {
when(work1.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS);
syncSubscriber.hookOnSubscribe(subscription);
verify(subscription).request(work1.getNumberOfEvents());
verify(work1).start();
assertEquals(0, syncSubscriber.getWorkQueueSize());
}
/**
* A work gets queued in work queue.
*/
@Test
public void queueWorkTest() {
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, false, operationTimeout);
syncSubscriber.queueWork(work2);
assertEquals(2, syncSubscriber.getWorkQueueSize());
}
/**
* Verifies that this processes multiple work items and current work encounter timeout
*/
@Test
public void processesMultipleWorkItemsAndCurrentWorkTimeout() {
final ServiceBusReceivedMessage message1 = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message2 = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message3 = mock(ServiceBusReceivedMessage.class);
final AtomicBoolean isTerminal = new AtomicBoolean(false);
final AtomicInteger remaining = new AtomicInteger(NUMBER_OF_WORK_ITEMS);
doAnswer(invocation -> {
ServiceBusReceivedMessage arg = invocation.getArgument(0);
if (arg == message1 || arg == message2) {
remaining.decrementAndGet();
return true;
} else {
return false;
}
}).when(work1).emitNext(any(ServiceBusReceivedMessage.class));
doAnswer(invocation -> isTerminal.get()).when(work1).isTerminal();
doAnswer(invocation -> remaining.get()).when(work1).getRemainingEvents();
when(work2.emitNext(message3)).thenReturn(true);
when(work2.isTerminal()).thenReturn(false);
final SynchronousReceiveWork work3 = mock(SynchronousReceiveWork.class);
when(work3.getId()).thenReturn(3L);
when(work3.getNumberOfEvents()).thenReturn(1);
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, false, operationTimeout);
syncSubscriber.queueWork(work2);
syncSubscriber.queueWork(work3);
syncSubscriber.hookOnSubscribe(subscription);
assertEquals(2, syncSubscriber.getWorkQueueSize());
syncSubscriber.hookOnNext(message1);
syncSubscriber.hookOnNext(message2);
isTerminal.set(true);
syncSubscriber.hookOnNext(message3);
verify(work2).start();
verify(work2).emitNext(message3);
assertEquals(1, syncSubscriber.getWorkQueueSize());
verify(subscription, times(2)).request(subscriptionArgumentCaptor.capture());
final List<Long> allRequests = subscriptionArgumentCaptor.getAllValues();
assertEquals(NUMBER_OF_WORK_ITEMS, allRequests.get(0));
final long requestedAfterWork1 = NUMBER_OF_WORK_ITEMS - remaining.get();
final long expectedDifference = work2.getNumberOfEvents() - requestedAfterWork1;
assertEquals(expectedDifference, allRequests.get(1));
}
/**
* Verifies that this processes multiple work items and current work can emit all messages successfully
*/
@Test
public void processesMultipleWorkItemsAndCurrentWorkEmitAllMessages() {
final ServiceBusReceivedMessage message1 = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message2 = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message3 = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message4 = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message5 = mock(ServiceBusReceivedMessage.class);
final AtomicBoolean isTerminal = new AtomicBoolean(false);
final AtomicInteger remaining = new AtomicInteger(NUMBER_OF_WORK_ITEMS);
doAnswer(invocation -> {
ServiceBusReceivedMessage arg = invocation.getArgument(0);
remaining.decrementAndGet();
if (arg == message4) {
isTerminal.set(true);
}
return true;
}).when(work1).emitNext(any(ServiceBusReceivedMessage.class));
doAnswer(invocation -> isTerminal.get()).when(work1).isTerminal();
doAnswer(invocation -> remaining.get()).when(work1).getRemainingEvents();
when(work2.isTerminal()).thenReturn(false);
when(work2.emitNext(message5)).thenReturn(true);
final SynchronousReceiveWork work3 = mock(SynchronousReceiveWork.class);
when(work3.getId()).thenReturn(3L);
when(work3.getNumberOfEvents()).thenReturn(1);
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, false, operationTimeout);
syncSubscriber.queueWork(work2);
syncSubscriber.queueWork(work3);
syncSubscriber.hookOnSubscribe(subscription);
assertEquals(2, syncSubscriber.getWorkQueueSize());
syncSubscriber.hookOnNext(message1);
syncSubscriber.hookOnNext(message2);
syncSubscriber.hookOnNext(message3);
syncSubscriber.hookOnNext(message4);
verify(work2).start();
syncSubscriber.hookOnNext(message5);
verify(work2).emitNext(message5);
assertEquals(1, syncSubscriber.getWorkQueueSize());
verify(subscription, times(2)).request(subscriptionArgumentCaptor.capture());
final List<Long> allRequests = subscriptionArgumentCaptor.getAllValues();
assertEquals(NUMBER_OF_WORK_ITEMS, allRequests.get(0));
assertEquals(NUMBER_OF_WORK_ITEMS_2, allRequests.get(1));
}
/**
* Verifies that all work items are completed if the subscriber is disposed.
*/
@Test
public void completesWorkOnCancel() {
when(work1.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS);
when(work2.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS_2);
syncSubscriber.queueWork(work2);
syncSubscriber.hookOnSubscribe(subscription);
syncSubscriber.hookOnCancel();
verify(work1).complete(any(String.class), isNull());
verify(work2).complete(any(String.class), isNull());
assertEquals(0, syncSubscriber.getWorkQueueSize());
}
/**
* Verifies that all work items are completed if the subscriber encounters an error.
*/
@Test
public void completesWorkOnError() {
final Throwable error = new AmqpException(false, "Test-error", new AmqpErrorContext("foo.com"));
when(work1.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS);
when(work2.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS_2);
syncSubscriber.queueWork(work2);
syncSubscriber.hookOnSubscribe(subscription);
syncSubscriber.hookOnError(error);
verify(work1).complete(any(String.class), eq(error));
verify(work2).complete(any(String.class), eq(error));
assertEquals(0, syncSubscriber.getWorkQueueSize());
}
@Test
public void releaseIfNoActiveReceive() {
when(work1.emitNext(any(ServiceBusReceivedMessage.class))).thenReturn(true);
final ServiceBusReceivedMessage message1beforeTimeout = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message2beforeTimeout = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message1afterTimeout = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message2afterTimeout = mock(ServiceBusReceivedMessage.class);
final AtomicBoolean isTerminal = new AtomicBoolean(false);
doAnswer(invocation -> isTerminal.get()).when(work1).isTerminal();
final AtomicInteger expectedReleaseCalls = new AtomicInteger(0);
final AtomicBoolean hadUnexpectedReleaseCall = new AtomicBoolean(false);
doAnswer(invocation -> {
ServiceBusReceivedMessage arg = invocation.getArgument(0);
if (arg == message1afterTimeout || arg == message2afterTimeout) {
expectedReleaseCalls.incrementAndGet();
} else {
hadUnexpectedReleaseCall.set(true);
}
return Mono.empty();
}).when(asyncClient).release(any(ServiceBusReceivedMessage.class));
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, true, operationTimeout);
syncSubscriber.hookOnSubscribe(subscription);
syncSubscriber.hookOnNext(message1beforeTimeout);
syncSubscriber.hookOnNext(message2beforeTimeout);
isTerminal.set(true);
syncSubscriber.hookOnNext(message1afterTimeout);
syncSubscriber.hookOnNext(message2afterTimeout);
verify(work1).emitNext(message1beforeTimeout);
verify(work1).emitNext(message2beforeTimeout);
verify(work1, never()).emitNext(message1afterTimeout);
verify(work1, never()).emitNext(message2afterTimeout);
assertEquals(2, expectedReleaseCalls.get());
assertFalse(hadUnexpectedReleaseCall.get());
}
} |
We can change it, though I don't know of anything that uses `PortPolicy` | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl());
if (overwrite || urlBuilder.getPort() == null) {
LOGGER.log(LogLevel.VERBOSE, () -> "Changing port to " + port);
try {
context.getHttpRequest().setUrl(urlBuilder.setPort(port).toUrl());
} catch (MalformedURLException e) {
return Mono.error(new RuntimeException("Failed to set the HTTP request port to " + port + ".", e));
}
}
return next.process();
} | return Mono.error(new RuntimeException("Failed to set the HTTP request port to " + port + ".", e)); | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl());
if (overwrite || urlBuilder.getPort() == null) {
LOGGER.log(LogLevel.VERBOSE, () -> "Changing port to " + port);
try {
context.getHttpRequest().setUrl(urlBuilder.setPort(port).toUrl());
} catch (MalformedURLException e) {
return Mono.error(new RuntimeException("Failed to set the HTTP request port to " + port + ".", e));
}
}
return next.process();
} | class PortPolicy implements HttpPipelinePolicy {
private static final ClientLogger LOGGER = new ClientLogger(PortPolicy.class);
private final int port;
private final boolean overwrite;
/**
* Creates a new PortPolicy object.
*
* @param port The port to set.
* @param overwrite Whether to overwrite a {@link HttpRequest HttpRequest's} port if it already has one.
*/
public PortPolicy(int port, boolean overwrite) {
this.port = port;
this.overwrite = overwrite;
}
@Override
} | class PortPolicy implements HttpPipelinePolicy {
private static final ClientLogger LOGGER = new ClientLogger(PortPolicy.class);
private final int port;
private final boolean overwrite;
/**
* Creates a new PortPolicy object.
*
* @param port The port to set.
* @param overwrite Whether to overwrite a {@link HttpRequest HttpRequest's} port if it already has one.
*/
public PortPolicy(int port, boolean overwrite) {
this.port = port;
this.overwrite = overwrite;
}
@Override
} |
Actually when we use new a instance of `SynchronousReceiveWork`, the `getCompleteEmitter()` won't be null. Because `work1` is a mock instance: ``` @Mock private SynchronousReceiveWork work1; ``` So I need mock `getCompleteEmitter()` return `completeEmitter1` to avoid nullpointer Exception when use this method in `SynchronousMessageSubscriber` | public void setup() {
mocksCloseable = MockitoAnnotations.openMocks(this);
when(work1.getId()).thenReturn(WORK_ID);
when(work1.getNumberOfEvents()).thenReturn(NUMBER_OF_WORK_ITEMS);
completeEmitter1 = Sinks.empty();
when(work1.getCompleteEmitter()).thenReturn(completeEmitter1);
when(work2.getId()).thenReturn(WORK_ID_2);
when(work2.getNumberOfEvents()).thenReturn(NUMBER_OF_WORK_ITEMS_2);
completeEmitter2 = Sinks.empty();
when(work2.getCompleteEmitter()).thenReturn(completeEmitter2);
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, false, operationTimeout);
} | when(work1.getCompleteEmitter()).thenReturn(completeEmitter1); | public void setup() {
mocksCloseable = MockitoAnnotations.openMocks(this);
when(work1.getId()).thenReturn(WORK_ID);
when(work1.getNumberOfEvents()).thenReturn(NUMBER_OF_WORK_ITEMS);
when(work2.getId()).thenReturn(WORK_ID_2);
when(work2.getNumberOfEvents()).thenReturn(NUMBER_OF_WORK_ITEMS_2);
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, false, operationTimeout);
} | class SynchronousMessageSubscriberTest {
private static final long WORK_ID = 10L;
private static final long WORK_ID_2 = 10L;
private static final int NUMBER_OF_WORK_ITEMS = 4;
private static final int NUMBER_OF_WORK_ITEMS_2 = 3;
private final Duration operationTimeout = Duration.ofSeconds(10);
@Mock
private ServiceBusReceiverAsyncClient asyncClient;
@Mock
private SynchronousReceiveWork work1;
@Mock
private SynchronousReceiveWork work2;
@Mock
private Subscription subscription;
@Captor
private ArgumentCaptor<Long> subscriptionArgumentCaptor;
private SynchronousMessageSubscriber syncSubscriber;
private AutoCloseable mocksCloseable;
private Sinks.Empty<Void> completeEmitter1;
private Sinks.Empty<Void> completeEmitter2;
@BeforeEach
@AfterEach
public void teardown() throws Exception {
if (mocksCloseable != null) {
mocksCloseable.close();
}
syncSubscriber.dispose();
Mockito.framework().clearInlineMock(this);
}
/**
* Verify that the initial subscription requests work1's number of work items.
*/
@Test
public void workAddedAndRequestedUpstream() {
when(work1.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS);
syncSubscriber.hookOnSubscribe(subscription);
verify(subscription).request(work1.getNumberOfEvents());
verify(work1).start();
assertEquals(0, syncSubscriber.getWorkQueueSize());
}
/**
* A work gets queued in work queue.
*/
@Test
public void queueWorkTest() {
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, false, operationTimeout);
syncSubscriber.queueWork(work2);
assertEquals(2, syncSubscriber.getWorkQueueSize());
}
/**
* Verifies that this processes multiple work items.
*/
@Test
public void processesMultipleWorkItems() {
final SynchronousReceiveWork work3 = mock(SynchronousReceiveWork.class);
when(work3.getId()).thenReturn(3L);
when(work3.getNumberOfEvents()).thenReturn(1);
when(work3.getCompleteEmitter()).thenReturn(Sinks.empty());
final ServiceBusReceivedMessage message1 = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message2 = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message3 = mock(ServiceBusReceivedMessage.class);
final AtomicBoolean isTerminal = new AtomicBoolean(false);
final AtomicInteger remaining = new AtomicInteger(NUMBER_OF_WORK_ITEMS);
doAnswer(invocation -> {
ServiceBusReceivedMessage arg = invocation.getArgument(0);
if (arg == message1 || arg == message2) {
remaining.decrementAndGet();
return true;
} else {
return false;
}
}).when(work1).emitNext(any(ServiceBusReceivedMessage.class));
doAnswer(invocation -> isTerminal.get()).when(work1).isTerminal();
doAnswer(invocation -> remaining.get()).when(work1).getRemainingEvents();
when(work2.emitNext(message3)).thenReturn(true);
when(work2.isTerminal()).thenReturn(false);
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, false, operationTimeout);
syncSubscriber.queueWork(work2);
syncSubscriber.queueWork(work3);
syncSubscriber.hookOnSubscribe(subscription);
assertEquals(2, syncSubscriber.getWorkQueueSize());
syncSubscriber.hookOnNext(message1);
syncSubscriber.hookOnNext(message2);
isTerminal.set(true);
syncSubscriber.hookOnNext(message3);
verify(work2).start();
verify(work2).emitNext(message3);
assertEquals(1, syncSubscriber.getWorkQueueSize());
verify(subscription, times(2)).request(subscriptionArgumentCaptor.capture());
final List<Long> allRequests = subscriptionArgumentCaptor.getAllValues();
final Set<Long> expected = new HashSet<>();
expected.add((long) work1.getNumberOfEvents());
final long requestedAfterWork1 = NUMBER_OF_WORK_ITEMS - remaining.get();
final long expectedDifference = work2.getNumberOfEvents() - requestedAfterWork1;
expected.add(expectedDifference);
assertEquals(expected.size(), allRequests.size());
allRequests.forEach(r -> assertTrue(expected.contains(r)));
}
/**
* Verifies that when previous work have completed, update current work
*/
@Test
public void updateCurrentWorkWhenQueueIsNotEmpty() {
final SynchronousReceiveWork work3 = mock(SynchronousReceiveWork.class);
when(work3.getId()).thenReturn(3L);
when(work3.getNumberOfEvents()).thenReturn(1);
when(work3.getCompleteEmitter()).thenReturn(Sinks.empty());
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, false, operationTimeout);
syncSubscriber.queueWork(work2);
syncSubscriber.queueWork(work3);
assertEquals(3, syncSubscriber.getWorkQueueSize());
syncSubscriber.hookOnSubscribe(subscription);
assertEquals(2, syncSubscriber.getWorkQueueSize());
when(work1.isTerminal()).thenReturn(true);
completeEmitter1.emitEmpty(Sinks.EmitFailureHandler.FAIL_FAST);
verify(work2).start();
assertEquals(1, syncSubscriber.getWorkQueueSize());
when(work2.isTerminal()).thenReturn(true);
completeEmitter2.emitEmpty(Sinks.EmitFailureHandler.FAIL_FAST);
verify(work3).start();
assertEquals(0, syncSubscriber.getWorkQueueSize());
}
/**
* Verifies that all work items are completed if the subscriber is disposed.
*/
@Test
public void completesWorkOnCancel() {
when(work1.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS);
when(work2.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS_2);
syncSubscriber.queueWork(work2);
syncSubscriber.hookOnSubscribe(subscription);
syncSubscriber.hookOnCancel();
verify(work1).complete(any(String.class), isNull());
verify(work2).complete(any(String.class), isNull());
assertEquals(0, syncSubscriber.getWorkQueueSize());
}
/**
* Verifies that all work items are completed if the subscriber encounters an error.
*/
@Test
public void completesWorkOnError() {
final Throwable error = new AmqpException(false, "Test-error", new AmqpErrorContext("foo.com"));
when(work1.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS);
when(work2.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS_2);
syncSubscriber.queueWork(work2);
syncSubscriber.hookOnSubscribe(subscription);
syncSubscriber.hookOnError(error);
verify(work1).complete(any(String.class), eq(error));
verify(work2).complete(any(String.class), eq(error));
assertEquals(0, syncSubscriber.getWorkQueueSize());
}
@Test
public void releaseIfNoActiveReceive() {
when(work1.emitNext(any(ServiceBusReceivedMessage.class))).thenReturn(true);
final ServiceBusReceivedMessage message1beforeTimeout = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message2beforeTimeout = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message1afterTimeout = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message2afterTimeout = mock(ServiceBusReceivedMessage.class);
final AtomicBoolean isTerminal = new AtomicBoolean(false);
doAnswer(invocation -> isTerminal.get()).when(work1).isTerminal();
final AtomicInteger expectedReleaseCalls = new AtomicInteger(0);
final AtomicBoolean hadUnexpectedReleaseCall = new AtomicBoolean(false);
doAnswer(invocation -> {
ServiceBusReceivedMessage arg = invocation.getArgument(0);
if (arg == message1afterTimeout || arg == message2afterTimeout) {
expectedReleaseCalls.incrementAndGet();
} else {
hadUnexpectedReleaseCall.set(true);
}
return Mono.empty();
}).when(asyncClient).release(any(ServiceBusReceivedMessage.class));
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, true, operationTimeout);
syncSubscriber.hookOnSubscribe(subscription);
syncSubscriber.hookOnNext(message1beforeTimeout);
syncSubscriber.hookOnNext(message2beforeTimeout);
isTerminal.set(true);
syncSubscriber.hookOnNext(message1afterTimeout);
syncSubscriber.hookOnNext(message2afterTimeout);
verify(work1).emitNext(message1beforeTimeout);
verify(work1).emitNext(message2beforeTimeout);
verify(work1, never()).emitNext(message1afterTimeout);
verify(work1, never()).emitNext(message2afterTimeout);
assertEquals(2, expectedReleaseCalls.get());
assertFalse(hadUnexpectedReleaseCall.get());
}
} | class SynchronousMessageSubscriberTest {
private static final long WORK_ID = 10L;
private static final long WORK_ID_2 = 10L;
private static final int NUMBER_OF_WORK_ITEMS = 4;
private static final int NUMBER_OF_WORK_ITEMS_2 = 3;
private final Duration operationTimeout = Duration.ofSeconds(10);
@Mock
private ServiceBusReceiverAsyncClient asyncClient;
@Mock
private SynchronousReceiveWork work1;
@Mock
private SynchronousReceiveWork work2;
@Mock
private Subscription subscription;
@Captor
private ArgumentCaptor<Long> subscriptionArgumentCaptor;
private SynchronousMessageSubscriber syncSubscriber;
private AutoCloseable mocksCloseable;
@BeforeEach
@AfterEach
public void teardown() throws Exception {
if (mocksCloseable != null) {
mocksCloseable.close();
}
syncSubscriber.dispose();
Mockito.framework().clearInlineMock(this);
}
/**
* Verify that the initial subscription requests work1's number of work items.
*/
@Test
public void workAddedAndRequestedUpstream() {
when(work1.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS);
syncSubscriber.hookOnSubscribe(subscription);
verify(subscription).request(work1.getNumberOfEvents());
verify(work1).start();
assertEquals(0, syncSubscriber.getWorkQueueSize());
}
/**
* A work gets queued in work queue.
*/
@Test
public void queueWorkTest() {
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, false, operationTimeout);
syncSubscriber.queueWork(work2);
assertEquals(2, syncSubscriber.getWorkQueueSize());
}
/**
* Verifies that this processes multiple work items and current work encounter timeout
*/
@Test
public void processesMultipleWorkItemsAndCurrentWorkTimeout() {
final ServiceBusReceivedMessage message1 = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message2 = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message3 = mock(ServiceBusReceivedMessage.class);
final AtomicBoolean isTerminal = new AtomicBoolean(false);
final AtomicInteger remaining = new AtomicInteger(NUMBER_OF_WORK_ITEMS);
doAnswer(invocation -> {
ServiceBusReceivedMessage arg = invocation.getArgument(0);
if (arg == message1 || arg == message2) {
remaining.decrementAndGet();
return true;
} else {
return false;
}
}).when(work1).emitNext(any(ServiceBusReceivedMessage.class));
doAnswer(invocation -> isTerminal.get()).when(work1).isTerminal();
doAnswer(invocation -> remaining.get()).when(work1).getRemainingEvents();
when(work2.emitNext(message3)).thenReturn(true);
when(work2.isTerminal()).thenReturn(false);
final SynchronousReceiveWork work3 = mock(SynchronousReceiveWork.class);
when(work3.getId()).thenReturn(3L);
when(work3.getNumberOfEvents()).thenReturn(1);
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, false, operationTimeout);
syncSubscriber.queueWork(work2);
syncSubscriber.queueWork(work3);
syncSubscriber.hookOnSubscribe(subscription);
assertEquals(2, syncSubscriber.getWorkQueueSize());
syncSubscriber.hookOnNext(message1);
syncSubscriber.hookOnNext(message2);
isTerminal.set(true);
syncSubscriber.hookOnNext(message3);
verify(work2).start();
verify(work2).emitNext(message3);
assertEquals(1, syncSubscriber.getWorkQueueSize());
verify(subscription, times(2)).request(subscriptionArgumentCaptor.capture());
final List<Long> allRequests = subscriptionArgumentCaptor.getAllValues();
assertEquals(NUMBER_OF_WORK_ITEMS, allRequests.get(0));
final long requestedAfterWork1 = NUMBER_OF_WORK_ITEMS - remaining.get();
final long expectedDifference = work2.getNumberOfEvents() - requestedAfterWork1;
assertEquals(expectedDifference, allRequests.get(1));
}
/**
* Verifies that this processes multiple work items and current work can emit all messages successfully
*/
@Test
public void processesMultipleWorkItemsAndCurrentWorkEmitAllMessages() {
final ServiceBusReceivedMessage message1 = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message2 = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message3 = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message4 = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message5 = mock(ServiceBusReceivedMessage.class);
final AtomicBoolean isTerminal = new AtomicBoolean(false);
final AtomicInteger remaining = new AtomicInteger(NUMBER_OF_WORK_ITEMS);
doAnswer(invocation -> {
ServiceBusReceivedMessage arg = invocation.getArgument(0);
remaining.decrementAndGet();
if (arg == message4) {
isTerminal.set(true);
}
return true;
}).when(work1).emitNext(any(ServiceBusReceivedMessage.class));
doAnswer(invocation -> isTerminal.get()).when(work1).isTerminal();
doAnswer(invocation -> remaining.get()).when(work1).getRemainingEvents();
when(work2.isTerminal()).thenReturn(false);
when(work2.emitNext(message5)).thenReturn(true);
final SynchronousReceiveWork work3 = mock(SynchronousReceiveWork.class);
when(work3.getId()).thenReturn(3L);
when(work3.getNumberOfEvents()).thenReturn(1);
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, false, operationTimeout);
syncSubscriber.queueWork(work2);
syncSubscriber.queueWork(work3);
syncSubscriber.hookOnSubscribe(subscription);
assertEquals(2, syncSubscriber.getWorkQueueSize());
syncSubscriber.hookOnNext(message1);
syncSubscriber.hookOnNext(message2);
syncSubscriber.hookOnNext(message3);
syncSubscriber.hookOnNext(message4);
verify(work2).start();
syncSubscriber.hookOnNext(message5);
verify(work2).emitNext(message5);
assertEquals(1, syncSubscriber.getWorkQueueSize());
verify(subscription, times(2)).request(subscriptionArgumentCaptor.capture());
final List<Long> allRequests = subscriptionArgumentCaptor.getAllValues();
assertEquals(NUMBER_OF_WORK_ITEMS, allRequests.get(0));
assertEquals(NUMBER_OF_WORK_ITEMS_2, allRequests.get(1));
}
/**
* Verifies that all work items are completed if the subscriber is disposed.
*/
@Test
public void completesWorkOnCancel() {
when(work1.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS);
when(work2.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS_2);
syncSubscriber.queueWork(work2);
syncSubscriber.hookOnSubscribe(subscription);
syncSubscriber.hookOnCancel();
verify(work1).complete(any(String.class), isNull());
verify(work2).complete(any(String.class), isNull());
assertEquals(0, syncSubscriber.getWorkQueueSize());
}
/**
* Verifies that all work items are completed if the subscriber encounters an error.
*/
@Test
public void completesWorkOnError() {
final Throwable error = new AmqpException(false, "Test-error", new AmqpErrorContext("foo.com"));
when(work1.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS);
when(work2.getRemainingEvents()).thenReturn(NUMBER_OF_WORK_ITEMS_2);
syncSubscriber.queueWork(work2);
syncSubscriber.hookOnSubscribe(subscription);
syncSubscriber.hookOnError(error);
verify(work1).complete(any(String.class), eq(error));
verify(work2).complete(any(String.class), eq(error));
assertEquals(0, syncSubscriber.getWorkQueueSize());
}
@Test
public void releaseIfNoActiveReceive() {
when(work1.emitNext(any(ServiceBusReceivedMessage.class))).thenReturn(true);
final ServiceBusReceivedMessage message1beforeTimeout = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message2beforeTimeout = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message1afterTimeout = mock(ServiceBusReceivedMessage.class);
final ServiceBusReceivedMessage message2afterTimeout = mock(ServiceBusReceivedMessage.class);
final AtomicBoolean isTerminal = new AtomicBoolean(false);
doAnswer(invocation -> isTerminal.get()).when(work1).isTerminal();
final AtomicInteger expectedReleaseCalls = new AtomicInteger(0);
final AtomicBoolean hadUnexpectedReleaseCall = new AtomicBoolean(false);
doAnswer(invocation -> {
ServiceBusReceivedMessage arg = invocation.getArgument(0);
if (arg == message1afterTimeout || arg == message2afterTimeout) {
expectedReleaseCalls.incrementAndGet();
} else {
hadUnexpectedReleaseCall.set(true);
}
return Mono.empty();
}).when(asyncClient).release(any(ServiceBusReceivedMessage.class));
syncSubscriber = new SynchronousMessageSubscriber(asyncClient, work1, true, operationTimeout);
syncSubscriber.hookOnSubscribe(subscription);
syncSubscriber.hookOnNext(message1beforeTimeout);
syncSubscriber.hookOnNext(message2beforeTimeout);
isTerminal.set(true);
syncSubscriber.hookOnNext(message1afterTimeout);
syncSubscriber.hookOnNext(message2afterTimeout);
verify(work1).emitNext(message1beforeTimeout);
verify(work1).emitNext(message2beforeTimeout);
verify(work1, never()).emitNext(message1afterTimeout);
verify(work1, never()).emitNext(message2afterTimeout);
assertEquals(2, expectedReleaseCalls.get());
assertFalse(hadUnexpectedReleaseCall.get());
}
} |
indent | protected void doHealthCheck(Health.Builder builder) {
if (this.producerAsyncClient == null && this.consumerAsyncClient == null) {
builder.withDetail("No client configured", "No Event Hub producer or consumer clients found.");
return;
}
if (this.producerAsyncClient != null) {
producerAsyncClient.getEventHubProperties()
.map(p -> builder.up())
.block(timeout);
} else {
consumerAsyncClient.getEventHubProperties()
.map(p -> builder.up())
.block(timeout);
}
} | .block(timeout); | protected void doHealthCheck(Health.Builder builder) {
if (this.producerAsyncClient == null && this.consumerAsyncClient == null) {
builder.withDetail("No client configured", "No Event Hub producer or consumer clients found.");
return;
}
if (this.producerAsyncClient != null) {
producerAsyncClient.getEventHubProperties()
.map(p -> builder.up())
.block(timeout);
} else {
consumerAsyncClient.getEventHubProperties()
.map(p -> builder.up())
.block(timeout);
}
} | class EventHubsHealthIndicator extends AbstractHealthIndicator {
private final EventHubProducerAsyncClient producerAsyncClient;
private final EventHubConsumerAsyncClient consumerAsyncClient;
private Duration timeout = DEFAULT_HEALTH_CHECK_TIMEOUT;
/**
* Creates a new instance of {@link EventHubsHealthIndicator}.
* @param producerAsyncClient the producer client
* @param consumerAsyncClient the consumer client
*/
public EventHubsHealthIndicator(EventHubProducerAsyncClient producerAsyncClient,
EventHubConsumerAsyncClient consumerAsyncClient) {
this.producerAsyncClient = producerAsyncClient;
this.consumerAsyncClient = consumerAsyncClient;
}
@Override
/**
* Set health check request timeout.
* @param timeout the duration value.
*/
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
} | class EventHubsHealthIndicator extends AbstractHealthIndicator {
private final EventHubProducerAsyncClient producerAsyncClient;
private final EventHubConsumerAsyncClient consumerAsyncClient;
private Duration timeout = DEFAULT_HEALTH_CHECK_TIMEOUT;
/**
* Creates a new instance of {@link EventHubsHealthIndicator}.
* @param producerAsyncClient the producer client
* @param consumerAsyncClient the consumer client
*/
public EventHubsHealthIndicator(EventHubProducerAsyncClient producerAsyncClient,
EventHubConsumerAsyncClient consumerAsyncClient) {
this.producerAsyncClient = producerAsyncClient;
this.consumerAsyncClient = consumerAsyncClient;
}
@Override
/**
* Set health check request timeout.
* @param timeout the duration value.
*/
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
} |
Done. | protected void doHealthCheck(Health.Builder builder) {
if (this.producerAsyncClient == null && this.consumerAsyncClient == null) {
builder.withDetail("No client configured", "No Event Hub producer or consumer clients found.");
return;
}
if (this.producerAsyncClient != null) {
producerAsyncClient.getEventHubProperties()
.map(p -> builder.up())
.block(timeout);
} else {
consumerAsyncClient.getEventHubProperties()
.map(p -> builder.up())
.block(timeout);
}
} | .block(timeout); | protected void doHealthCheck(Health.Builder builder) {
if (this.producerAsyncClient == null && this.consumerAsyncClient == null) {
builder.withDetail("No client configured", "No Event Hub producer or consumer clients found.");
return;
}
if (this.producerAsyncClient != null) {
producerAsyncClient.getEventHubProperties()
.map(p -> builder.up())
.block(timeout);
} else {
consumerAsyncClient.getEventHubProperties()
.map(p -> builder.up())
.block(timeout);
}
} | class EventHubsHealthIndicator extends AbstractHealthIndicator {
private final EventHubProducerAsyncClient producerAsyncClient;
private final EventHubConsumerAsyncClient consumerAsyncClient;
private Duration timeout = DEFAULT_HEALTH_CHECK_TIMEOUT;
/**
* Creates a new instance of {@link EventHubsHealthIndicator}.
* @param producerAsyncClient the producer client
* @param consumerAsyncClient the consumer client
*/
public EventHubsHealthIndicator(EventHubProducerAsyncClient producerAsyncClient,
EventHubConsumerAsyncClient consumerAsyncClient) {
this.producerAsyncClient = producerAsyncClient;
this.consumerAsyncClient = consumerAsyncClient;
}
@Override
/**
* Set health check request timeout.
* @param timeout the duration value.
*/
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
} | class EventHubsHealthIndicator extends AbstractHealthIndicator {
private final EventHubProducerAsyncClient producerAsyncClient;
private final EventHubConsumerAsyncClient consumerAsyncClient;
private Duration timeout = DEFAULT_HEALTH_CHECK_TIMEOUT;
/**
* Creates a new instance of {@link EventHubsHealthIndicator}.
* @param producerAsyncClient the producer client
* @param consumerAsyncClient the consumer client
*/
public EventHubsHealthIndicator(EventHubProducerAsyncClient producerAsyncClient,
EventHubConsumerAsyncClient consumerAsyncClient) {
this.producerAsyncClient = producerAsyncClient;
this.consumerAsyncClient = consumerAsyncClient;
}
@Override
/**
* Set health check request timeout.
* @param timeout the duration value.
*/
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
} |
I remove this code here for two reason base on my understanding: 1. the work in queue is never started, so it won't be terminated except the subscriber disposed. 2. the work in queue won't send request, so we if add the remaining to current REQUESTED, it may be wrong. The difference has been calculate when try to `requestUpstream()`. | private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
} | if (currentWork != null && !currentWork.isTerminal()) { | private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, currentWork.getId())
.addKeyValue("numberOfEvents", currentWork.getNumberOfEvents())
.log("This work from queue is terminal. Skip it.");
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
}
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
}
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} |
This seems to be the successfully complete current work case. Where does code go if current work timeout or killed? | private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
} | if (numberRequested == 0L) { | private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
}
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, currentWork.getId())
.addKeyValue("numberOfEvents", currentWork.getNumberOfEvents())
.log("This work from queue is terminal. Skip it.");
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
}
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} |
I assume after `getOrUpdateCurrentWork` called, next work in queue become current work, and requested number updated, this Subscriber will need to get into the `drain/drainQueue` loop again? Do we know whether this is the case, and where in code this happens? | private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
} | getOrUpdateCurrentWork(); | private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
}
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, currentWork.getId())
.addKeyValue("numberOfEvents", currentWork.getNumberOfEvents())
.log("This work from queue is terminal. Skip it.");
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
}
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} |
If current work timeout, as you could see in the diagram I provided, the current work will be updated in the line: [SynchronousMessageSubscriber.java#L202](https://github.com/Azure/azure-sdk-for-java/blob/982b06d7163536c5aefc15be641ba52e9cbdf2fe/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/SynchronousMessageSubscriber.java#L202) If receive thread is killed, the work won't be killed because it is scheduled on reactor thread. So the work keep receiving message till complete. But no downstream on that work anymore, this is another issue currently I am looking at, "how to tell the current work if the receive thread is killed". | private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
} | if (numberRequested == 0L) { | private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
}
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, currentWork.getId())
.addKeyValue("numberOfEvents", currentWork.getNumberOfEvents())
.log("This work from queue is terminal. Skip it.");
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
}
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} |
>after getOrUpdateCurrentWork called, next work in queue become current work, and requested number updated This is right. But `numberRequested==0L` block is not in loop, so `drain/drainQueue` return after requested number updated. Only when next message received, it will trigger this `drain/drainQueue` method again. | private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
} | getOrUpdateCurrentWork(); | private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
}
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, currentWork.getId())
.addKeyValue("numberOfEvents", currentWork.getNumberOfEvents())
.log("This work from queue is terminal. Skip it.");
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
}
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} |
The `hookOnNext` method? | private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
} | getOrUpdateCurrentWork(); | private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
}
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, currentWork.getId())
.addKeyValue("numberOfEvents", currentWork.getNumberOfEvents())
.log("This work from queue is terminal. Skip it.");
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
}
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} |
yes, the receive flow: ondelivery -> hookOnNext -> drain -> drainQueue | private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
} | getOrUpdateCurrentWork(); | private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
}
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, currentWork.getId())
.addKeyValue("numberOfEvents", currentWork.getNumberOfEvents())
.log("This work from queue is terminal. Skip it.");
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
}
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} |
Thinking a bit more, currently the work timeout start at the time when work start. which means if 2 works to process, for the 2nd work, receiveMessage() timeout = 1st work timeout + 2nd work timeout. Should the work timeout start at the time we put the work into queue? | private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
} | if (currentWork != null && !currentWork.isTerminal()) { | private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, currentWork.getId())
.addKeyValue("numberOfEvents", currentWork.getNumberOfEvents())
.log("This work from queue is terminal. Skip it.");
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
}
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
}
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} |
This seems depends on the design, on multiple thread call the iterator. And whether the timeout is for network (that message requested but not able to receive), or for user (that stream called but not able to progress as work still in queue, maybe because a prior thread still receiving a few million message?) | private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
} | if (currentWork != null && !currentWork.isTerminal()) { | private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, currentWork.getId())
.addKeyValue("numberOfEvents", currentWork.getNumberOfEvents())
.log("This work from queue is terminal. Skip it.");
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
}
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
}
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} |
Yes, this was a design choice made. The typical application use case is "obtain_one_iterable -> iterate -> iteration_completed", then repeat, the cycle is serial. Even if the application obtains multiple "Iterables", it can iterate only one "Iterable" at a time, which we call "Active-Iterable". The current "Active-Iterable" has to terminate for the next "Iterable" already in the scope to become "Active-Iterable". So the design was to start the timer only when an Iterable transition to "Active-Iterable" | private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
} | if (currentWork != null && !currentWork.isTerminal()) { | private SynchronousReceiveWork getOrUpdateCurrentWork() {
synchronized (currentWorkLock) {
if (currentWork != null && !currentWork.isTerminal()) {
return currentWork;
}
currentWork = workQueue.poll();
while (currentWork != null && currentWork.isTerminal()) {
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, currentWork.getId())
.addKeyValue("numberOfEvents", currentWork.getNumberOfEvents())
.log("This work from queue is terminal. Skip it.");
currentWork = workQueue.poll();
}
if (currentWork != null) {
final SynchronousReceiveWork work = currentWork;
logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.log("Current work updated.");
work.start();
requestUpstream(work.getNumberOfEvents());
}
return currentWork;
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
}
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} | class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessage> {
private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicInteger wip = new AtomicInteger();
private final ConcurrentLinkedQueue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<ServiceBusReceivedMessage> bufferMessages = new ConcurrentLinkedDeque<>();
private final Object currentWorkLock = new Object();
private final ServiceBusReceiverAsyncClient asyncClient;
private final boolean isPrefetchDisabled;
private final Duration operationTimeout;
private volatile SynchronousReceiveWork currentWork;
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<SynchronousMessageSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class,
"upstream");
/**
* Creates a synchronous subscriber with some initial work to queue.
*
*
* @param asyncClient Client to update disposition of messages.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
* @param initialWork Initial work to queue.
*
* <p>
* When {@code isPrefetchDisabled} is true, we release the messages those received during the timespan
* between the last terminated downstream and the next active downstream.
* </p>
*
* @throws NullPointerException if {@code initialWork} is null.
* @throws IllegalArgumentException if {@code initialWork.getNumberOfEvents()} is less than 1.
*/
SynchronousMessageSubscriber(ServiceBusReceiverAsyncClient asyncClient,
SynchronousReceiveWork initialWork,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.workQueue.add(Objects.requireNonNull(initialWork, "'initialWork' cannot be null."));
this.isPrefetchDisabled = isPrefetchDisabled;
if (initialWork.getNumberOfEvents() < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'numberOfEvents' cannot be less than 1. Actual: " + initialWork.getNumberOfEvents()));
}
Operators.addCap(REQUESTED, this, initialWork.getNumberOfEvents());
}
/**
* On an initial subscription, will take the first work item, and request that amount of work for it.
*
* @param subscription Subscription for upstream.
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
logger.warning("This should only be subscribed to once. Ignoring subscription.");
return;
}
getOrUpdateCurrentWork();
subscription.request(REQUESTED.get(this));
}
/**
* Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of
* the subscriber.
*
* @param message Event to publish.
*/
@Override
protected void hookOnNext(ServiceBusReceivedMessage message) {
if (isTerminated()) {
Operators.onNextDropped(message, Context.empty());
} else {
bufferMessages.add(message);
drain();
}
}
/**
* Queue the work to be picked up by drain loop.
*
* @param work to be queued.
*/
void queueWork(SynchronousReceiveWork work) {
Objects.requireNonNull(work, "'work' cannot be null");
workQueue.add(work);
LoggingEventBuilder logBuilder = logger.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.addKeyValue("numberOfEvents", work.getNumberOfEvents())
.addKeyValue("timeout", work.getTimeout());
if (workQueue.peek() == work && (currentWork == null || currentWork.isTerminal())) {
logBuilder.log("First work in queue. Requesting upstream if needed.");
getOrUpdateCurrentWork();
} else {
logBuilder.log("Queuing receive work.");
}
if (UPSTREAM.get(this) != null) {
drain();
}
}
/**
* Drain the work, only one thread can be in this loop at a time.
*/
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
try {
drainQueue();
} finally {
missed = wip.addAndGet(-missed);
}
}
}
/***
* Drain the queue using a lock on current work in progress.
*/
private void drainQueue() {
if (isTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = bufferMessages.isEmpty();
SynchronousReceiveWork currentDownstream = null;
while (numberRequested != 0L && !isEmpty) {
if (isTerminated()) {
break;
}
long numberConsumed = 0L;
while (numberRequested != numberConsumed) {
if (isEmpty || isTerminated()) {
break;
}
final ServiceBusReceivedMessage message = bufferMessages.poll();
boolean isEmitted = false;
while (!isEmitted) {
currentDownstream = getOrUpdateCurrentWork();
if (currentDownstream == null) {
break;
}
isEmitted = currentDownstream.emitNext(message);
}
if (!isEmitted) {
if (isPrefetchDisabled) {
asyncClient.release(message).subscribe(__ -> { },
error -> logger.atWarning()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Couldn't release the message.", error),
() -> logger.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, message.getLockToken())
.log("Message successfully released."));
} else {
bufferMessages.addFirst(message);
break;
}
}
numberConsumed++;
isEmpty = bufferMessages.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberConsumed);
}
}
if (numberRequested == 0L) {
logger.atVerbose()
.log("Current work is completed. Schedule next work.");
getOrUpdateCurrentWork();
}
}
/**
* {@inheritDoc}
*/
@Override
protected void hookOnError(Throwable throwable) {
dispose("Errors occurred upstream", throwable);
}
@Override
protected void hookOnCancel() {
this.dispose();
}
private boolean isTerminated() {
if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
return true;
}
return isDisposed.get();
}
/**
* Gets the current work item if it is not terminal and cleans up any existing timeout operations.
*
* @return Gets or sets the next work item. Null if there are no work items currently.
*/
/**
* Adds additional credits upstream if {@code numberOfMessages} is greater than the number of {@code REQUESTED}
* items.
*
* @param numberOfMessages Number of messages required downstream.
*/
private void requestUpstream(long numberOfMessages) {
if (isTerminated()) {
logger.info("Cannot request more messages upstream. Subscriber is terminated.");
return;
}
final Subscription subscription = UPSTREAM.get(this);
if (subscription == null) {
logger.info("There is no upstream to request messages from.");
return;
}
final long currentRequested = REQUESTED.get(this);
final long difference = numberOfMessages - currentRequested;
logger.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, currentRequested)
.addKeyValue("numberOfMessages", numberOfMessages)
.addKeyValue("difference", difference)
.log("Requesting messages from upstream.");
if (difference <= 0) {
return;
}
Operators.addCap(REQUESTED, this, difference);
subscription.request(difference);
}
@Override
public void dispose() {
super.dispose();
dispose("Upstream completed the receive work.", null);
}
private void dispose(String message, Throwable throwable) {
super.dispose();
if (isDisposed.getAndSet(true)) {
return;
}
synchronized (currentWorkLock) {
if (currentWork != null) {
currentWork.complete(message, throwable);
currentWork = null;
}
SynchronousReceiveWork w = workQueue.poll();
while (w != null) {
w.complete(message, throwable);
w = workQueue.poll();
}
}
}
/**
* package-private method to check queue size.
*
* @return The current number of items in the queue.
*/
int getWorkQueueSize() {
return this.workQueue.size();
}
} |
if configuration is nullable why do we have `Configuration.NONE` ? How's `NONE` different from `null`? | public static ProxyOptions fromConfiguration(Configuration configuration) {
if (configuration == Configuration.NONE) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException(INVALID_CONFIGURATION_MESSAGE));
}
Configuration proxyConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
boolean createUnresolved = proxyConfiguration.get(Properties.CREATE_UNRESOLVED);
return attemptToLoadProxy(proxyConfiguration, createUnresolved);
} | if (configuration == Configuration.NONE) { | public static ProxyOptions fromConfiguration(Configuration configuration) {
return fromConfiguration(configuration, false);
} | class ProxyOptions {
private static final ClientLogger LOGGER = new ClientLogger(ProxyOptions.class);
private static final String INVALID_CONFIGURATION_MESSAGE = "'configuration' cannot be 'Configuration.NONE'.";
private static final String INVALID_AZURE_PROXY_URL = "Configuration {} is an invalid URL and is being ignored.";
/*
* This indicates whether system proxy configurations (HTTPS_PROXY, HTTP_PROXY) are allowed to be used.
*/
private static final String JAVA_SYSTEM_PROXY_PREREQUISITE = "java.net.useSystemProxies";
private static final int DEFAULT_HTTPS_PORT = 443;
private static final int DEFAULT_HTTP_PORT = 80;
/*
* The 'http.nonProxyHosts' system property is expected to be delimited by '|', but don't split escaped '|'s.
*/
private static final Pattern HTTP_NON_PROXY_HOSTS_SPLIT = Pattern.compile("(?<!\\\\)\\|");
/*
* The 'NO_PROXY' environment variable is expected to be delimited by ',', but don't split escaped ','s.
*/
private static final Pattern NO_PROXY_SPLIT = Pattern.compile("(?<!\\\\),");
private static final Pattern UNESCAPED_PERIOD = Pattern.compile("(?<!\\\\)\\.");
private static final Pattern ANY = Pattern.compile("\\*");
private final InetSocketAddress address;
private final Type type;
private String username;
private String password;
private String nonProxyHosts;
/**
* Creates ProxyOptions.
*
* @param type the proxy type
* @param address the proxy address (ip and port number)
*/
public ProxyOptions(Type type, InetSocketAddress address) {
this.type = type;
this.address = address;
}
/**
* Set the proxy credentials.
*
* @param username proxy user name
* @param password proxy password
* @return the updated ProxyOptions object
*/
public ProxyOptions setCredentials(String username, String password) {
this.username = Objects.requireNonNull(username, "'username' cannot be null.");
this.password = Objects.requireNonNull(password, "'password' cannot be null.");
return this;
}
/**
* Sets the hosts which bypass the proxy.
* <p>
* The expected format of the passed string is a {@code '|'} delimited list of hosts which should bypass the proxy.
* Individual host strings may contain regex characters such as {@code '*'}.
*
* @param nonProxyHosts Hosts that bypass the proxy.
* @return the updated ProxyOptions object
*/
public ProxyOptions setNonProxyHosts(String nonProxyHosts) {
this.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHosts);
return this;
}
/**
* @return the address of the proxy.
*/
public InetSocketAddress getAddress() {
return address;
}
/**
* @return the type of the proxy.
*/
public Type getType() {
return type;
}
/**
* @return the proxy user name.
*/
public String getUsername() {
return this.username;
}
/**
* @return the proxy password.
*/
public String getPassword() {
return this.password;
}
/**
* @return the hosts that bypass the proxy.
*/
public String getNonProxyHosts() {
return this.nonProxyHosts;
}
/**
* Attempts to load a proxy from the environment.
* <p>
* If a proxy is found and loaded the proxy address is DNS resolved.
* <p>
* Environment configurations are loaded in this order:
* <ol>
* <li>Azure HTTPS</li>
* <li>Azure HTTP</li>
* <li>Java HTTPS</li>
* <li>Java HTTP</li>
* </ol>
*
* Azure proxy configurations will be preferred over Java proxy configurations as they are more closely scoped to
* the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred.
*
* <p>
* {@code null} will be returned if no proxy was found in the environment.
*
* @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If
* {@code null} is passed then {@link Configuration
* Configuration
* @return A {@link ProxyOptions} reflecting a proxy loaded from the environment, if no proxy is found {@code null}
* will be returned.
* @throws IllegalArgumentException If {@code configuration} is {@link Configuration
*/
/**
* Attempts to load a proxy from the environment.
* <p>
* If a proxy is found and loaded, the proxy address is DNS resolved based on {@code createUnresolved}. When {@code
* createUnresolved} is true resolving {@link
* calls.
* <p>
* Environment configurations are loaded in this order:
* <ol>
* <li>Azure HTTPS</li>
* <li>Azure HTTP</li>
* <li>Java HTTPS</li>
* <li>Java HTTP</li>
* </ol>
*
* Azure proxy configurations will be preferred over Java proxy configurations as they are more closely scoped to
* the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred.
* <p>
* {@code null} will be returned if no proxy was found in the environment.
*
* @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If
* {@code null} is passed then {@link Configuration
* Configuration
* @param createUnresolved Flag determining whether the returned {@link ProxyOptions} is unresolved.
* @return A {@link ProxyOptions} reflecting a proxy loaded from the environment, if no proxy is found {@code null}
* will be returned.
* @throws IllegalArgumentException If {@code configuration} is {@link Configuration
*/
public static ProxyOptions fromConfiguration(Configuration configuration, boolean createUnresolved) {
if (configuration == Configuration.NONE) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException(INVALID_CONFIGURATION_MESSAGE));
}
Configuration proxyConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
return attemptToLoadProxy(proxyConfiguration, createUnresolved);
}
private static ProxyOptions attemptToLoadProxy(Configuration configuration, boolean createUnresolved) {
ProxyOptions proxyOptions;
if (Boolean.parseBoolean(configuration.get(JAVA_SYSTEM_PROXY_PREREQUISITE))) {
proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTPS_PROXY);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from HTTPS_PROXY environment variable.");
return proxyOptions;
}
proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTP_PROXY);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from HTTP_PROXY environment variable.");
return proxyOptions;
}
}
proxyOptions = attemptToLoadJavaProxy(configuration, createUnresolved,
Properties.HTTPS_PROXY_HOST, Properties.HTTPS_PROXY_PORT, Properties.HTTPS_PROXY_USER, Properties.HTTPS_PROXY_PASSWORD, DEFAULT_HTTPS_PORT);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from JVM HTTPS system properties.");
return proxyOptions;
}
proxyOptions = attemptToLoadJavaProxy(configuration, createUnresolved,
Properties.HTTP_PROXY_HOST, Properties.HTTP_PROXY_PORT, Properties.HTTP_PROXY_USER, Properties.HTTP_PROXY_PASSWORD, DEFAULT_HTTP_PORT);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from JVM HTTP system properties.");
return proxyOptions;
}
return null;
}
private static ProxyOptions attemptToLoadSystemProxy(Configuration configuration, boolean createUnresolved,
String proxyProperty) {
String proxyConfiguration = configuration.get(proxyProperty);
if (CoreUtils.isNullOrEmpty(proxyConfiguration)) {
return null;
}
try {
URL proxyUrl = new URL(proxyConfiguration);
int port = (proxyUrl.getPort() == -1) ? proxyUrl.getDefaultPort() : proxyUrl.getPort();
InetSocketAddress socketAddress = (createUnresolved)
? InetSocketAddress.createUnresolved(proxyUrl.getHost(), port)
: new InetSocketAddress(proxyUrl.getHost(), port);
ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, socketAddress);
String nonProxyHostsString = configuration.get(Configuration.PROPERTY_NO_PROXY);
if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) {
proxyOptions.nonProxyHosts = sanitizeNoProxy(nonProxyHostsString);
LOGGER.log(LogLevel.VERBOSE, () -> "Using non-proxy host regex: " + proxyOptions.nonProxyHosts);
}
String userInfo = proxyUrl.getUserInfo();
if (userInfo != null) {
String[] usernamePassword = userInfo.split(":", 2);
if (usernamePassword.length == 2) {
try {
proxyOptions.setCredentials(
URLDecoder.decode(usernamePassword[0], StandardCharsets.UTF_8.toString()),
URLDecoder.decode(usernamePassword[1], StandardCharsets.UTF_8.toString())
);
} catch (UnsupportedEncodingException e) {
return null;
}
}
}
return proxyOptions;
} catch (MalformedURLException ex) {
LOGGER.warning(INVALID_AZURE_PROXY_URL, proxyProperty);
return null;
}
}
/*
* Helper function that sanitizes 'NO_PROXY' into a Pattern safe string.
*/
static String sanitizeNoProxy(String noProxyString) {
return sanitizeNonProxyHosts(NO_PROXY_SPLIT.split(noProxyString));
}
private static ProxyOptions attemptToLoadJavaProxy(Configuration configuration, boolean createUnresolved,
ConfigurationProperty<String> hostProperty,
ConfigurationProperty<Integer> portProperty,
ConfigurationProperty<String> userProperty,
ConfigurationProperty<String> passwordProperty,
Integer defaultPort) {
String host = configuration.get(hostProperty);
if (CoreUtils.isNullOrEmpty(host)) {
return null;
}
int port;
try {
port = configuration.get(portProperty);
} catch (NumberFormatException ex) {
port = defaultPort;
}
InetSocketAddress socketAddress = (createUnresolved)
? InetSocketAddress.createUnresolved(host, port)
: new InetSocketAddress(host, port);
ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, socketAddress);
String nonProxyHostsString = configuration.get(Properties.NO_PROXY);
if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) {
proxyOptions.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHostsString);
LOGGER.log(LogLevel.VERBOSE, () -> "Using non-proxy host regex: " + proxyOptions.nonProxyHosts);
}
String username = configuration.get(userProperty);
String password = configuration.get(passwordProperty);
if (username != null && password != null) {
proxyOptions.setCredentials(username, password);
}
return proxyOptions;
}
/*
* Helper function that sanitizes 'http.nonProxyHosts' into a Pattern safe string.
*/
static String sanitizeJavaHttpNonProxyHosts(String nonProxyHostsString) {
return sanitizeNonProxyHosts(HTTP_NON_PROXY_HOSTS_SPLIT.split(nonProxyHostsString));
}
private static String sanitizeNonProxyHosts(String[] nonProxyHosts) {
StringBuilder sanitizedBuilder = new StringBuilder();
for (int i = 0; i < nonProxyHosts.length; i++) {
if (i > 0) {
sanitizedBuilder.append("|");
}
String prefixWildcard = "";
String suffixWildcard = "";
String sanitizedNonProxyHost = nonProxyHosts[i];
/*
* If the non-proxy host begins with either '.', '*', '.*', or any of the previous with a trailing '?'
* substring the non-proxy host and set the wildcard prefix.
*/
if (sanitizedNonProxyHost.startsWith(".")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1);
} else if (sanitizedNonProxyHost.startsWith(".?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
} else if (sanitizedNonProxyHost.startsWith("*?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
} else if (sanitizedNonProxyHost.startsWith("*")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1);
} else if (sanitizedNonProxyHost.startsWith(".*?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(3);
} else if (sanitizedNonProxyHost.startsWith(".*")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
}
/*
* Same with the ending of the non-proxy host, if it has a suffix wildcard trim the non-proxy host and
* retain the suffix wildcard.
*/
if (sanitizedNonProxyHost.endsWith(".")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2);
} else if (sanitizedNonProxyHost.endsWith(".?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
} else if (sanitizedNonProxyHost.endsWith("*?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
} else if (sanitizedNonProxyHost.endsWith("*")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2);
} else if (sanitizedNonProxyHost.endsWith(".*?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 4);
} else if (sanitizedNonProxyHost.endsWith(".*")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
}
try {
String attemptToSanitizeAsRegex = sanitizedNonProxyHost;
attemptToSanitizeAsRegex = UNESCAPED_PERIOD.matcher(attemptToSanitizeAsRegex).replaceAll("\\\\.");
attemptToSanitizeAsRegex = ANY.matcher(attemptToSanitizeAsRegex).replaceAll("\\.*?");
sanitizedNonProxyHost = Pattern.compile(attemptToSanitizeAsRegex).pattern();
} catch (PatternSyntaxException ex) {
/*
* Replace the non-proxy host with the sanitized value.
*
* The body of the non-proxy host is quoted to handle scenarios such a '127.0.0.1' or '*.azure.com'
* where without quoting the '.' in the string would be treated as the match any character instead of
* the literal '.' character.
*/
sanitizedNonProxyHost = Pattern.quote(sanitizedNonProxyHost);
}
sanitizedBuilder.append("(")
.append(prefixWildcard)
.append(sanitizedNonProxyHost)
.append(suffixWildcard)
.append(")");
}
return sanitizedBuilder.toString();
}
/**
* The type of the proxy.
*/
public enum Type {
/**
* HTTP proxy type.
*/
HTTP(Proxy.Type.HTTP),
/**
* SOCKS4 proxy type.
*/
SOCKS4(Proxy.Type.SOCKS),
/**
* SOCKS5 proxy type.
*/
SOCKS5(Proxy.Type.SOCKS);
private final Proxy.Type proxyType;
Type(Proxy.Type proxyType) {
this.proxyType = proxyType;
}
/**
* Get the {@link Proxy.Type} equivalent of this type.
*
* @return the proxy type
*/
public Proxy.Type toProxyType() {
return proxyType;
}
}
private static class Properties {
public static final ConfigurationProperty<String> NO_PROXY = ConfigurationProperty.stringPropertyBuilder("http.proxy.non-proxy-hosts")
.environmentAliases("http.nonProxyHosts", Configuration.PROPERTY_NO_PROXY)
.canLogValue(true)
.build();
public static final ConfigurationProperty<Boolean> CREATE_UNRESOLVED = ConfigurationUtils.booleanSharedPropertyBuilder("http.proxy.create-unresolved")
.defaultValue(false)
.build();
public static final ConfigurationProperty<String> HTTP_PROXY_HOST = ConfigurationUtils.stringSharedPropertyBuilder("http.proxy.host")
.environmentAliases("http.proxyHost")
.canLogValue(true)
.build();
public static final ConfigurationProperty<Integer> HTTP_PROXY_PORT = ConfigurationUtils.integerSharedPropertyBuilder("http.proxy.port")
.environmentAliases("http.proxyPort")
.defaultValue(DEFAULT_HTTP_PORT)
.build();
public static final ConfigurationProperty<String> HTTP_PROXY_USER = ConfigurationUtils.stringSharedPropertyBuilder("http.proxy.username")
.environmentAliases("http.proxyUser")
.build();
public static final ConfigurationProperty<String> HTTP_PROXY_PASSWORD = ConfigurationUtils.stringSharedPropertyBuilder("http.proxy.password")
.environmentAliases("http.proxyPassword")
.build();
public static final ConfigurationProperty<String> HTTPS_PROXY_HOST = ConfigurationUtils.stringSharedPropertyBuilder("https.proxy.host")
.environmentAliases("https.proxyHost")
.canLogValue(true)
.build();
public static final ConfigurationProperty<Integer> HTTPS_PROXY_PORT = ConfigurationUtils.integerSharedPropertyBuilder("https.proxy.port")
.environmentAliases("https.proxyPort")
.defaultValue(DEFAULT_HTTPS_PORT)
.build();
public static final ConfigurationProperty<String> HTTPS_PROXY_USER = ConfigurationUtils.stringSharedPropertyBuilder("https.proxy.username")
.environmentAliases("https.proxyUser")
.build();
public static final ConfigurationProperty<String> HTTPS_PROXY_PASSWORD = ConfigurationUtils.stringSharedPropertyBuilder("https.proxy.password")
.environmentAliases("https.proxyPassword")
.build();
}
} | class ProxyOptions {
private static final ClientLogger LOGGER = new ClientLogger(ProxyOptions.class);
private static final String INVALID_AZURE_PROXY_URL = "Configuration {} is an invalid URL and is being ignored.";
/*
* This indicates whether system proxy configurations (HTTPS_PROXY, HTTP_PROXY) are allowed to be used.
*/
private static final String JAVA_SYSTEM_PROXY_PREREQUISITE = "java.net.useSystemProxies";
/*
* Java environment variables related to proxies. The protocol is removed since these are the same for 'https' and
* 'http', the exception is 'http.nonProxyHosts' as it is used for both.
*/
private static final String JAVA_PROXY_HOST = "proxyHost";
private static final String JAVA_PROXY_PORT = "proxyPort";
private static final String JAVA_PROXY_USER = "proxyUser";
private static final String JAVA_PROXY_PASSWORD = "proxyPassword";
private static final String JAVA_NON_PROXY_HOSTS = "http.nonProxyHosts";
private static final String HTTPS = "https";
private static final int DEFAULT_HTTPS_PORT = 443;
private static final String HTTP = "http";
private static final int DEFAULT_HTTP_PORT = 80;
/*
* The 'http.nonProxyHosts' system property is expected to be delimited by '|', but don't split escaped '|'s.
*/
private static final Pattern HTTP_NON_PROXY_HOSTS_SPLIT = Pattern.compile("(?<!\\\\)\\|");
/*
* The 'NO_PROXY' environment variable is expected to be delimited by ',', but don't split escaped ','s.
*/
private static final Pattern NO_PROXY_SPLIT = Pattern.compile("(?<!\\\\),");
private static final Pattern UNESCAPED_PERIOD = Pattern.compile("(?<!\\\\)\\.");
private static final Pattern ANY = Pattern.compile("\\*");
private static final ConfigurationProperty<String> NON_PROXY_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_NON_PROXY_HOSTS)
.shared(true)
.logValue(true)
.build();
private static final ConfigurationProperty<String> HOST_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_HOST)
.shared(true)
.logValue(true)
.build();
private static final ConfigurationProperty<Integer> PORT_PROPERTY = ConfigurationPropertyBuilder.ofInteger(ConfigurationProperties.HTTP_PROXY_PORT)
.shared(true)
.defaultValue(DEFAULT_HTTPS_PORT)
.build();
private static final ConfigurationProperty<String> USER_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_USER)
.shared(true)
.logValue(true)
.build();
private static final ConfigurationProperty<String> PASSWORD_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_PASSWORD)
.shared(true)
.build();
private final InetSocketAddress address;
private final Type type;
private String username;
private String password;
private String nonProxyHosts;
/**
* Creates ProxyOptions.
*
* @param type the proxy type
* @param address the proxy address (ip and port number)
*/
public ProxyOptions(Type type, InetSocketAddress address) {
this.type = type;
this.address = address;
}
/**
* Set the proxy credentials.
*
* @param username proxy user name
* @param password proxy password
* @return the updated ProxyOptions object
*/
public ProxyOptions setCredentials(String username, String password) {
this.username = Objects.requireNonNull(username, "'username' cannot be null.");
this.password = Objects.requireNonNull(password, "'password' cannot be null.");
return this;
}
/**
* Sets the hosts which bypass the proxy.
* <p>
* The expected format of the passed string is a {@code '|'} delimited list of hosts which should bypass the proxy.
* Individual host strings may contain regex characters such as {@code '*'}.
*
* @param nonProxyHosts Hosts that bypass the proxy.
* @return the updated ProxyOptions object
*/
public ProxyOptions setNonProxyHosts(String nonProxyHosts) {
this.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHosts);
return this;
}
/**
* @return the address of the proxy.
*/
public InetSocketAddress getAddress() {
return address;
}
/**
* @return the type of the proxy.
*/
public Type getType() {
return type;
}
/**
* @return the proxy user name.
*/
public String getUsername() {
return this.username;
}
/**
* @return the proxy password.
*/
public String getPassword() {
return this.password;
}
/**
* @return the hosts that bypass the proxy.
*/
public String getNonProxyHosts() {
return this.nonProxyHosts;
}
/**
* Attempts to load a proxy from the configuration.
* <p>
* If a proxy is found and loaded the proxy address is DNS resolved.
* <p>
* Environment configurations are loaded in this order:
* <ol>
* <li>Azure HTTPS</li>
* <li>Azure HTTP</li>
* <li>Java HTTPS</li>
* <li>Java HTTP</li>
* </ol>
*
* Azure proxy configurations will be preferred over Java proxy configurations as they are more closely scoped to
* the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred.
*
* <p>
* {@code null} will be returned if no proxy was found in the environment.
*
* @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If
* {@code null} is passed then {@link Configuration
* @return A {@link ProxyOptions} reflecting a proxy loaded from the environment, if no proxy is found {@code null}
* will be returned.
*/
/**
* Attempts to load a proxy from the environment.
* <p>
* If a proxy is found and loaded, the proxy address is DNS resolved based on {@code createUnresolved}. When {@code
* createUnresolved} is true resolving {@link
* calls.
* <p>
* Environment configurations are loaded in this order:
* <ol>
* <li>Azure HTTPS</li>
* <li>Azure HTTP</li>
* <li>Java HTTPS</li>
* <li>Java HTTP</li>
* </ol>
*
* Azure proxy configurations will be preferred over Java proxy configurations as they are more closely scoped to
* the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred.
* <p>
* {@code null} will be returned if no proxy was found in the environment.
*
* @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If
* {@code null} is passed then {@link Configuration
* Configuration
* @param createUnresolved Flag determining whether the returned {@link ProxyOptions} is unresolved.
* @return A {@link ProxyOptions} reflecting a proxy loaded from the environment, if no proxy is found {@code null}
* will be returned.
*/
public static ProxyOptions fromConfiguration(Configuration configuration, boolean createUnresolved) {
Configuration proxyConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
return attemptToLoadProxy(proxyConfiguration, createUnresolved);
}
private static ProxyOptions attemptToLoadProxy(Configuration configuration, boolean createUnresolved) {
if (configuration == Configuration.NONE) {
return null;
}
ProxyOptions proxyOptions = null;
if (Boolean.parseBoolean(configuration.get(JAVA_SYSTEM_PROXY_PREREQUISITE))) {
proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTPS_PROXY);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from HTTPS_PROXY environment variable.");
return proxyOptions;
}
proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTP_PROXY);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from HTTP_PROXY environment variable.");
return proxyOptions;
}
}
proxyOptions = attemptToLoadAzureSdkProxy(configuration, createUnresolved);
if (proxyOptions != null) {
return proxyOptions;
}
proxyOptions = attemptToLoadJavaProxy(configuration, createUnresolved, HTTPS);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from JVM HTTPS system properties.");
return proxyOptions;
}
proxyOptions = attemptToLoadJavaProxy(configuration, createUnresolved, HTTP);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from JVM HTTP system properties.");
return proxyOptions;
}
return null;
}
private static ProxyOptions attemptToLoadSystemProxy(Configuration configuration, boolean createUnresolved,
String proxyProperty) {
String proxyConfiguration = configuration.get(proxyProperty);
if (CoreUtils.isNullOrEmpty(proxyConfiguration)) {
return null;
}
try {
URL proxyUrl = new URL(proxyConfiguration);
int port = (proxyUrl.getPort() == -1) ? proxyUrl.getDefaultPort() : proxyUrl.getPort();
InetSocketAddress socketAddress = (createUnresolved)
? InetSocketAddress.createUnresolved(proxyUrl.getHost(), port)
: new InetSocketAddress(proxyUrl.getHost(), port);
ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, socketAddress);
String nonProxyHostsString = configuration.get(Configuration.PROPERTY_NO_PROXY);
if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) {
proxyOptions.nonProxyHosts = sanitizeNoProxy(nonProxyHostsString);
LOGGER.log(LogLevel.VERBOSE, () -> "Using non-proxy host regex: " + proxyOptions.nonProxyHosts);
}
String userInfo = proxyUrl.getUserInfo();
if (userInfo != null) {
String[] usernamePassword = userInfo.split(":", 2);
if (usernamePassword.length == 2) {
try {
proxyOptions.setCredentials(
URLDecoder.decode(usernamePassword[0], StandardCharsets.UTF_8.toString()),
URLDecoder.decode(usernamePassword[1], StandardCharsets.UTF_8.toString())
);
} catch (UnsupportedEncodingException e) {
return null;
}
}
}
return proxyOptions;
} catch (MalformedURLException ex) {
LOGGER.warning(INVALID_AZURE_PROXY_URL, proxyProperty);
return null;
}
}
/*
* Helper function that sanitizes 'NO_PROXY' into a Pattern safe string.
*/
static String sanitizeNoProxy(String noProxyString) {
return sanitizeNonProxyHosts(NO_PROXY_SPLIT.split(noProxyString));
}
private static ProxyOptions attemptToLoadJavaProxy(Configuration configuration, boolean createUnresolved,
String type) {
String host = configuration.get(type + "." + JAVA_PROXY_HOST);
if (CoreUtils.isNullOrEmpty(host)) {
return null;
}
int port;
try {
port = Integer.parseInt(configuration.get(type + "." + JAVA_PROXY_PORT));
} catch (NumberFormatException ex) {
port = HTTPS.equals(type) ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT;
}
String nonProxyHostsString = configuration.get(JAVA_NON_PROXY_HOSTS);
String username = configuration.get(type + "." + JAVA_PROXY_USER);
String password = configuration.get(type + "." + JAVA_PROXY_PASSWORD);
return createOptions(host, port, nonProxyHostsString, username, password, createUnresolved);
}
private static ProxyOptions attemptToLoadAzureSdkProxy(Configuration configuration, boolean createUnresolved) {
String host = configuration.get(HOST_PROPERTY);
if (CoreUtils.isNullOrEmpty(host)) {
return null;
}
int port = configuration.get(PORT_PROPERTY);
String nonProxyHostsString = configuration.get(NON_PROXY_PROPERTY);
String username = configuration.get(USER_PROPERTY);
String password = configuration.get(PASSWORD_PROPERTY);
return createOptions(host, port, nonProxyHostsString, username, password, createUnresolved);
}
private static ProxyOptions createOptions(String host, int port, String nonProxyHostsString, String username, String password, boolean createUnresolved) {
InetSocketAddress socketAddress = (createUnresolved)
? InetSocketAddress.createUnresolved(host, port)
: new InetSocketAddress(host, port);
ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, socketAddress);
if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) {
proxyOptions.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHostsString);
LOGGER.log(LogLevel.VERBOSE, () -> "Using non-proxy host regex: " + proxyOptions.nonProxyHosts);
}
if (username != null && password != null) {
proxyOptions.setCredentials(username, password);
}
return proxyOptions;
}
/*
* Helper function that sanitizes 'http.nonProxyHosts' into a Pattern safe string.
*/
static String sanitizeJavaHttpNonProxyHosts(String nonProxyHostsString) {
return sanitizeNonProxyHosts(HTTP_NON_PROXY_HOSTS_SPLIT.split(nonProxyHostsString));
}
private static String sanitizeNonProxyHosts(String[] nonProxyHosts) {
StringBuilder sanitizedBuilder = new StringBuilder();
for (int i = 0; i < nonProxyHosts.length; i++) {
if (i > 0) {
sanitizedBuilder.append("|");
}
String prefixWildcard = "";
String suffixWildcard = "";
String sanitizedNonProxyHost = nonProxyHosts[i];
/*
* If the non-proxy host begins with either '.', '*', '.*', or any of the previous with a trailing '?'
* substring the non-proxy host and set the wildcard prefix.
*/
if (sanitizedNonProxyHost.startsWith(".")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1);
} else if (sanitizedNonProxyHost.startsWith(".?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
} else if (sanitizedNonProxyHost.startsWith("*?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
} else if (sanitizedNonProxyHost.startsWith("*")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1);
} else if (sanitizedNonProxyHost.startsWith(".*?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(3);
} else if (sanitizedNonProxyHost.startsWith(".*")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
}
/*
* Same with the ending of the non-proxy host, if it has a suffix wildcard trim the non-proxy host and
* retain the suffix wildcard.
*/
if (sanitizedNonProxyHost.endsWith(".")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2);
} else if (sanitizedNonProxyHost.endsWith(".?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
} else if (sanitizedNonProxyHost.endsWith("*?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
} else if (sanitizedNonProxyHost.endsWith("*")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2);
} else if (sanitizedNonProxyHost.endsWith(".*?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 4);
} else if (sanitizedNonProxyHost.endsWith(".*")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
}
try {
String attemptToSanitizeAsRegex = sanitizedNonProxyHost;
attemptToSanitizeAsRegex = UNESCAPED_PERIOD.matcher(attemptToSanitizeAsRegex).replaceAll("\\\\.");
attemptToSanitizeAsRegex = ANY.matcher(attemptToSanitizeAsRegex).replaceAll("\\.*?");
sanitizedNonProxyHost = Pattern.compile(attemptToSanitizeAsRegex).pattern();
} catch (PatternSyntaxException ex) {
/*
* Replace the non-proxy host with the sanitized value.
*
* The body of the non-proxy host is quoted to handle scenarios such a '127.0.0.1' or '*.azure.com'
* where without quoting the '.' in the string would be treated as the match any character instead of
* the literal '.' character.
*/
sanitizedNonProxyHost = Pattern.quote(sanitizedNonProxyHost);
}
sanitizedBuilder.append("(")
.append(prefixWildcard)
.append(sanitizedNonProxyHost)
.append(suffixWildcard)
.append(")");
}
return sanitizedBuilder.toString();
}
/**
* The type of the proxy.
*/
public enum Type {
/**
* HTTP proxy type.
*/
HTTP(Proxy.Type.HTTP),
/**
* SOCKS4 proxy type.
*/
SOCKS4(Proxy.Type.SOCKS),
/**
* SOCKS5 proxy type.
*/
SOCKS5(Proxy.Type.SOCKS);
private final Proxy.Type proxyType;
Type(Proxy.Type proxyType) {
this.proxyType = proxyType;
}
/**
* Get the {@link Proxy.Type} equivalent of this type.
*
* @return the proxy type
*/
public Proxy.Type toProxyType() {
return proxyType;
}
}
/**
* Lists available configuration property names for HTTP {@link ProxyOptions}.
*/
private static class ConfigurationProperties {
/**
* Represents a list of hosts that should be reached directly, bypassing the proxy.
* This is a list of patterns separated by '|'. The patterns may start or end with a '*' for wildcards.
* Any host matching one of these patterns will be reached through a direct connection instead of through a proxy.
* <p>
* Default value is {@code null}
*/
public static final String HTTP_PROXY_NON_PROXY_HOSTS = "http.proxy.non-proxy-hosts";
/**
* The HTTP host name of the proxy server.
* <p>
* Default value is {@code null}.
*/
public static final String HTTP_PROXY_HOST = "http.proxy.hostname";
/**
* The port number of the proxy server.
* <p>
* Default value is {@code 443}.
*/
public static final String HTTP_PROXY_PORT = "http.proxy.port";
/**
* The HTTP proxy server user.
* Default value is {@code null}.
*/
public static final String HTTP_PROXY_USER = "http.proxy.username";
/**
* The HTTP proxy server password.
* Default value is {@code null}.
*/
public static final String HTTP_PROXY_PASSWORD = "http.proxy.password";
}
} |
this is an existing pattern we use everywhere, But I don't see how `Configuration.NONE` is different than null, I'll chat with @alzimmermsft once he's back to understand if we can improve something here. | public static ProxyOptions fromConfiguration(Configuration configuration) {
if (configuration == Configuration.NONE) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException(INVALID_CONFIGURATION_MESSAGE));
}
Configuration proxyConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
boolean createUnresolved = proxyConfiguration.get(Properties.CREATE_UNRESOLVED);
return attemptToLoadProxy(proxyConfiguration, createUnresolved);
} | if (configuration == Configuration.NONE) { | public static ProxyOptions fromConfiguration(Configuration configuration) {
return fromConfiguration(configuration, false);
} | class ProxyOptions {
private static final ClientLogger LOGGER = new ClientLogger(ProxyOptions.class);
private static final String INVALID_CONFIGURATION_MESSAGE = "'configuration' cannot be 'Configuration.NONE'.";
private static final String INVALID_AZURE_PROXY_URL = "Configuration {} is an invalid URL and is being ignored.";
/*
* This indicates whether system proxy configurations (HTTPS_PROXY, HTTP_PROXY) are allowed to be used.
*/
private static final String JAVA_SYSTEM_PROXY_PREREQUISITE = "java.net.useSystemProxies";
private static final int DEFAULT_HTTPS_PORT = 443;
private static final int DEFAULT_HTTP_PORT = 80;
/*
* The 'http.nonProxyHosts' system property is expected to be delimited by '|', but don't split escaped '|'s.
*/
private static final Pattern HTTP_NON_PROXY_HOSTS_SPLIT = Pattern.compile("(?<!\\\\)\\|");
/*
* The 'NO_PROXY' environment variable is expected to be delimited by ',', but don't split escaped ','s.
*/
private static final Pattern NO_PROXY_SPLIT = Pattern.compile("(?<!\\\\),");
private static final Pattern UNESCAPED_PERIOD = Pattern.compile("(?<!\\\\)\\.");
private static final Pattern ANY = Pattern.compile("\\*");
private final InetSocketAddress address;
private final Type type;
private String username;
private String password;
private String nonProxyHosts;
/**
* Creates ProxyOptions.
*
* @param type the proxy type
* @param address the proxy address (ip and port number)
*/
public ProxyOptions(Type type, InetSocketAddress address) {
this.type = type;
this.address = address;
}
/**
* Set the proxy credentials.
*
* @param username proxy user name
* @param password proxy password
* @return the updated ProxyOptions object
*/
public ProxyOptions setCredentials(String username, String password) {
this.username = Objects.requireNonNull(username, "'username' cannot be null.");
this.password = Objects.requireNonNull(password, "'password' cannot be null.");
return this;
}
/**
* Sets the hosts which bypass the proxy.
* <p>
* The expected format of the passed string is a {@code '|'} delimited list of hosts which should bypass the proxy.
* Individual host strings may contain regex characters such as {@code '*'}.
*
* @param nonProxyHosts Hosts that bypass the proxy.
* @return the updated ProxyOptions object
*/
public ProxyOptions setNonProxyHosts(String nonProxyHosts) {
this.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHosts);
return this;
}
/**
* @return the address of the proxy.
*/
public InetSocketAddress getAddress() {
return address;
}
/**
* @return the type of the proxy.
*/
public Type getType() {
return type;
}
/**
* @return the proxy user name.
*/
public String getUsername() {
return this.username;
}
/**
* @return the proxy password.
*/
public String getPassword() {
return this.password;
}
/**
* @return the hosts that bypass the proxy.
*/
public String getNonProxyHosts() {
return this.nonProxyHosts;
}
/**
* Attempts to load a proxy from the environment.
* <p>
* If a proxy is found and loaded the proxy address is DNS resolved.
* <p>
* Environment configurations are loaded in this order:
* <ol>
* <li>Azure HTTPS</li>
* <li>Azure HTTP</li>
* <li>Java HTTPS</li>
* <li>Java HTTP</li>
* </ol>
*
* Azure proxy configurations will be preferred over Java proxy configurations as they are more closely scoped to
* the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred.
*
* <p>
* {@code null} will be returned if no proxy was found in the environment.
*
* @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If
* {@code null} is passed then {@link Configuration
* Configuration
* @return A {@link ProxyOptions} reflecting a proxy loaded from the environment, if no proxy is found {@code null}
* will be returned.
* @throws IllegalArgumentException If {@code configuration} is {@link Configuration
*/
/**
* Attempts to load a proxy from the environment.
* <p>
* If a proxy is found and loaded, the proxy address is DNS resolved based on {@code createUnresolved}. When {@code
* createUnresolved} is true resolving {@link
* calls.
* <p>
* Environment configurations are loaded in this order:
* <ol>
* <li>Azure HTTPS</li>
* <li>Azure HTTP</li>
* <li>Java HTTPS</li>
* <li>Java HTTP</li>
* </ol>
*
* Azure proxy configurations will be preferred over Java proxy configurations as they are more closely scoped to
* the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred.
* <p>
* {@code null} will be returned if no proxy was found in the environment.
*
* @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If
* {@code null} is passed then {@link Configuration
* Configuration
* @param createUnresolved Flag determining whether the returned {@link ProxyOptions} is unresolved.
* @return A {@link ProxyOptions} reflecting a proxy loaded from the environment, if no proxy is found {@code null}
* will be returned.
* @throws IllegalArgumentException If {@code configuration} is {@link Configuration
*/
public static ProxyOptions fromConfiguration(Configuration configuration, boolean createUnresolved) {
if (configuration == Configuration.NONE) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException(INVALID_CONFIGURATION_MESSAGE));
}
Configuration proxyConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
return attemptToLoadProxy(proxyConfiguration, createUnresolved);
}
private static ProxyOptions attemptToLoadProxy(Configuration configuration, boolean createUnresolved) {
ProxyOptions proxyOptions;
if (Boolean.parseBoolean(configuration.get(JAVA_SYSTEM_PROXY_PREREQUISITE))) {
proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTPS_PROXY);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from HTTPS_PROXY environment variable.");
return proxyOptions;
}
proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTP_PROXY);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from HTTP_PROXY environment variable.");
return proxyOptions;
}
}
proxyOptions = attemptToLoadJavaProxy(configuration, createUnresolved,
Properties.HTTPS_PROXY_HOST, Properties.HTTPS_PROXY_PORT, Properties.HTTPS_PROXY_USER, Properties.HTTPS_PROXY_PASSWORD, DEFAULT_HTTPS_PORT);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from JVM HTTPS system properties.");
return proxyOptions;
}
proxyOptions = attemptToLoadJavaProxy(configuration, createUnresolved,
Properties.HTTP_PROXY_HOST, Properties.HTTP_PROXY_PORT, Properties.HTTP_PROXY_USER, Properties.HTTP_PROXY_PASSWORD, DEFAULT_HTTP_PORT);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from JVM HTTP system properties.");
return proxyOptions;
}
return null;
}
private static ProxyOptions attemptToLoadSystemProxy(Configuration configuration, boolean createUnresolved,
String proxyProperty) {
String proxyConfiguration = configuration.get(proxyProperty);
if (CoreUtils.isNullOrEmpty(proxyConfiguration)) {
return null;
}
try {
URL proxyUrl = new URL(proxyConfiguration);
int port = (proxyUrl.getPort() == -1) ? proxyUrl.getDefaultPort() : proxyUrl.getPort();
InetSocketAddress socketAddress = (createUnresolved)
? InetSocketAddress.createUnresolved(proxyUrl.getHost(), port)
: new InetSocketAddress(proxyUrl.getHost(), port);
ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, socketAddress);
String nonProxyHostsString = configuration.get(Configuration.PROPERTY_NO_PROXY);
if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) {
proxyOptions.nonProxyHosts = sanitizeNoProxy(nonProxyHostsString);
LOGGER.log(LogLevel.VERBOSE, () -> "Using non-proxy host regex: " + proxyOptions.nonProxyHosts);
}
String userInfo = proxyUrl.getUserInfo();
if (userInfo != null) {
String[] usernamePassword = userInfo.split(":", 2);
if (usernamePassword.length == 2) {
try {
proxyOptions.setCredentials(
URLDecoder.decode(usernamePassword[0], StandardCharsets.UTF_8.toString()),
URLDecoder.decode(usernamePassword[1], StandardCharsets.UTF_8.toString())
);
} catch (UnsupportedEncodingException e) {
return null;
}
}
}
return proxyOptions;
} catch (MalformedURLException ex) {
LOGGER.warning(INVALID_AZURE_PROXY_URL, proxyProperty);
return null;
}
}
/*
* Helper function that sanitizes 'NO_PROXY' into a Pattern safe string.
*/
static String sanitizeNoProxy(String noProxyString) {
return sanitizeNonProxyHosts(NO_PROXY_SPLIT.split(noProxyString));
}
private static ProxyOptions attemptToLoadJavaProxy(Configuration configuration, boolean createUnresolved,
ConfigurationProperty<String> hostProperty,
ConfigurationProperty<Integer> portProperty,
ConfigurationProperty<String> userProperty,
ConfigurationProperty<String> passwordProperty,
Integer defaultPort) {
String host = configuration.get(hostProperty);
if (CoreUtils.isNullOrEmpty(host)) {
return null;
}
int port;
try {
port = configuration.get(portProperty);
} catch (NumberFormatException ex) {
port = defaultPort;
}
InetSocketAddress socketAddress = (createUnresolved)
? InetSocketAddress.createUnresolved(host, port)
: new InetSocketAddress(host, port);
ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, socketAddress);
String nonProxyHostsString = configuration.get(Properties.NO_PROXY);
if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) {
proxyOptions.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHostsString);
LOGGER.log(LogLevel.VERBOSE, () -> "Using non-proxy host regex: " + proxyOptions.nonProxyHosts);
}
String username = configuration.get(userProperty);
String password = configuration.get(passwordProperty);
if (username != null && password != null) {
proxyOptions.setCredentials(username, password);
}
return proxyOptions;
}
/*
* Helper function that sanitizes 'http.nonProxyHosts' into a Pattern safe string.
*/
static String sanitizeJavaHttpNonProxyHosts(String nonProxyHostsString) {
return sanitizeNonProxyHosts(HTTP_NON_PROXY_HOSTS_SPLIT.split(nonProxyHostsString));
}
private static String sanitizeNonProxyHosts(String[] nonProxyHosts) {
StringBuilder sanitizedBuilder = new StringBuilder();
for (int i = 0; i < nonProxyHosts.length; i++) {
if (i > 0) {
sanitizedBuilder.append("|");
}
String prefixWildcard = "";
String suffixWildcard = "";
String sanitizedNonProxyHost = nonProxyHosts[i];
/*
* If the non-proxy host begins with either '.', '*', '.*', or any of the previous with a trailing '?'
* substring the non-proxy host and set the wildcard prefix.
*/
if (sanitizedNonProxyHost.startsWith(".")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1);
} else if (sanitizedNonProxyHost.startsWith(".?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
} else if (sanitizedNonProxyHost.startsWith("*?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
} else if (sanitizedNonProxyHost.startsWith("*")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1);
} else if (sanitizedNonProxyHost.startsWith(".*?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(3);
} else if (sanitizedNonProxyHost.startsWith(".*")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
}
/*
* Same with the ending of the non-proxy host, if it has a suffix wildcard trim the non-proxy host and
* retain the suffix wildcard.
*/
if (sanitizedNonProxyHost.endsWith(".")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2);
} else if (sanitizedNonProxyHost.endsWith(".?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
} else if (sanitizedNonProxyHost.endsWith("*?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
} else if (sanitizedNonProxyHost.endsWith("*")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2);
} else if (sanitizedNonProxyHost.endsWith(".*?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 4);
} else if (sanitizedNonProxyHost.endsWith(".*")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
}
try {
String attemptToSanitizeAsRegex = sanitizedNonProxyHost;
attemptToSanitizeAsRegex = UNESCAPED_PERIOD.matcher(attemptToSanitizeAsRegex).replaceAll("\\\\.");
attemptToSanitizeAsRegex = ANY.matcher(attemptToSanitizeAsRegex).replaceAll("\\.*?");
sanitizedNonProxyHost = Pattern.compile(attemptToSanitizeAsRegex).pattern();
} catch (PatternSyntaxException ex) {
/*
* Replace the non-proxy host with the sanitized value.
*
* The body of the non-proxy host is quoted to handle scenarios such a '127.0.0.1' or '*.azure.com'
* where without quoting the '.' in the string would be treated as the match any character instead of
* the literal '.' character.
*/
sanitizedNonProxyHost = Pattern.quote(sanitizedNonProxyHost);
}
sanitizedBuilder.append("(")
.append(prefixWildcard)
.append(sanitizedNonProxyHost)
.append(suffixWildcard)
.append(")");
}
return sanitizedBuilder.toString();
}
/**
* The type of the proxy.
*/
public enum Type {
/**
* HTTP proxy type.
*/
HTTP(Proxy.Type.HTTP),
/**
* SOCKS4 proxy type.
*/
SOCKS4(Proxy.Type.SOCKS),
/**
* SOCKS5 proxy type.
*/
SOCKS5(Proxy.Type.SOCKS);
private final Proxy.Type proxyType;
Type(Proxy.Type proxyType) {
this.proxyType = proxyType;
}
/**
* Get the {@link Proxy.Type} equivalent of this type.
*
* @return the proxy type
*/
public Proxy.Type toProxyType() {
return proxyType;
}
}
private static class Properties {
public static final ConfigurationProperty<String> NO_PROXY = ConfigurationProperty.stringPropertyBuilder("http.proxy.non-proxy-hosts")
.environmentAliases("http.nonProxyHosts", Configuration.PROPERTY_NO_PROXY)
.canLogValue(true)
.build();
public static final ConfigurationProperty<Boolean> CREATE_UNRESOLVED = ConfigurationUtils.booleanSharedPropertyBuilder("http.proxy.create-unresolved")
.defaultValue(false)
.build();
public static final ConfigurationProperty<String> HTTP_PROXY_HOST = ConfigurationUtils.stringSharedPropertyBuilder("http.proxy.host")
.environmentAliases("http.proxyHost")
.canLogValue(true)
.build();
public static final ConfigurationProperty<Integer> HTTP_PROXY_PORT = ConfigurationUtils.integerSharedPropertyBuilder("http.proxy.port")
.environmentAliases("http.proxyPort")
.defaultValue(DEFAULT_HTTP_PORT)
.build();
public static final ConfigurationProperty<String> HTTP_PROXY_USER = ConfigurationUtils.stringSharedPropertyBuilder("http.proxy.username")
.environmentAliases("http.proxyUser")
.build();
public static final ConfigurationProperty<String> HTTP_PROXY_PASSWORD = ConfigurationUtils.stringSharedPropertyBuilder("http.proxy.password")
.environmentAliases("http.proxyPassword")
.build();
public static final ConfigurationProperty<String> HTTPS_PROXY_HOST = ConfigurationUtils.stringSharedPropertyBuilder("https.proxy.host")
.environmentAliases("https.proxyHost")
.canLogValue(true)
.build();
public static final ConfigurationProperty<Integer> HTTPS_PROXY_PORT = ConfigurationUtils.integerSharedPropertyBuilder("https.proxy.port")
.environmentAliases("https.proxyPort")
.defaultValue(DEFAULT_HTTPS_PORT)
.build();
public static final ConfigurationProperty<String> HTTPS_PROXY_USER = ConfigurationUtils.stringSharedPropertyBuilder("https.proxy.username")
.environmentAliases("https.proxyUser")
.build();
public static final ConfigurationProperty<String> HTTPS_PROXY_PASSWORD = ConfigurationUtils.stringSharedPropertyBuilder("https.proxy.password")
.environmentAliases("https.proxyPassword")
.build();
}
} | class ProxyOptions {
private static final ClientLogger LOGGER = new ClientLogger(ProxyOptions.class);
private static final String INVALID_AZURE_PROXY_URL = "Configuration {} is an invalid URL and is being ignored.";
/*
* This indicates whether system proxy configurations (HTTPS_PROXY, HTTP_PROXY) are allowed to be used.
*/
private static final String JAVA_SYSTEM_PROXY_PREREQUISITE = "java.net.useSystemProxies";
/*
* Java environment variables related to proxies. The protocol is removed since these are the same for 'https' and
* 'http', the exception is 'http.nonProxyHosts' as it is used for both.
*/
private static final String JAVA_PROXY_HOST = "proxyHost";
private static final String JAVA_PROXY_PORT = "proxyPort";
private static final String JAVA_PROXY_USER = "proxyUser";
private static final String JAVA_PROXY_PASSWORD = "proxyPassword";
private static final String JAVA_NON_PROXY_HOSTS = "http.nonProxyHosts";
private static final String HTTPS = "https";
private static final int DEFAULT_HTTPS_PORT = 443;
private static final String HTTP = "http";
private static final int DEFAULT_HTTP_PORT = 80;
/*
* The 'http.nonProxyHosts' system property is expected to be delimited by '|', but don't split escaped '|'s.
*/
private static final Pattern HTTP_NON_PROXY_HOSTS_SPLIT = Pattern.compile("(?<!\\\\)\\|");
/*
* The 'NO_PROXY' environment variable is expected to be delimited by ',', but don't split escaped ','s.
*/
private static final Pattern NO_PROXY_SPLIT = Pattern.compile("(?<!\\\\),");
private static final Pattern UNESCAPED_PERIOD = Pattern.compile("(?<!\\\\)\\.");
private static final Pattern ANY = Pattern.compile("\\*");
private static final ConfigurationProperty<String> NON_PROXY_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_NON_PROXY_HOSTS)
.shared(true)
.logValue(true)
.build();
private static final ConfigurationProperty<String> HOST_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_HOST)
.shared(true)
.logValue(true)
.build();
private static final ConfigurationProperty<Integer> PORT_PROPERTY = ConfigurationPropertyBuilder.ofInteger(ConfigurationProperties.HTTP_PROXY_PORT)
.shared(true)
.defaultValue(DEFAULT_HTTPS_PORT)
.build();
private static final ConfigurationProperty<String> USER_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_USER)
.shared(true)
.logValue(true)
.build();
private static final ConfigurationProperty<String> PASSWORD_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_PASSWORD)
.shared(true)
.build();
private final InetSocketAddress address;
private final Type type;
private String username;
private String password;
private String nonProxyHosts;
/**
* Creates ProxyOptions.
*
* @param type the proxy type
* @param address the proxy address (ip and port number)
*/
public ProxyOptions(Type type, InetSocketAddress address) {
this.type = type;
this.address = address;
}
/**
* Set the proxy credentials.
*
* @param username proxy user name
* @param password proxy password
* @return the updated ProxyOptions object
*/
public ProxyOptions setCredentials(String username, String password) {
this.username = Objects.requireNonNull(username, "'username' cannot be null.");
this.password = Objects.requireNonNull(password, "'password' cannot be null.");
return this;
}
/**
* Sets the hosts which bypass the proxy.
* <p>
* The expected format of the passed string is a {@code '|'} delimited list of hosts which should bypass the proxy.
* Individual host strings may contain regex characters such as {@code '*'}.
*
* @param nonProxyHosts Hosts that bypass the proxy.
* @return the updated ProxyOptions object
*/
public ProxyOptions setNonProxyHosts(String nonProxyHosts) {
this.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHosts);
return this;
}
/**
* @return the address of the proxy.
*/
public InetSocketAddress getAddress() {
return address;
}
/**
* @return the type of the proxy.
*/
public Type getType() {
return type;
}
/**
* @return the proxy user name.
*/
public String getUsername() {
return this.username;
}
/**
* @return the proxy password.
*/
public String getPassword() {
return this.password;
}
/**
* @return the hosts that bypass the proxy.
*/
public String getNonProxyHosts() {
return this.nonProxyHosts;
}
/**
* Attempts to load a proxy from the configuration.
* <p>
* If a proxy is found and loaded the proxy address is DNS resolved.
* <p>
* Environment configurations are loaded in this order:
* <ol>
* <li>Azure HTTPS</li>
* <li>Azure HTTP</li>
* <li>Java HTTPS</li>
* <li>Java HTTP</li>
* </ol>
*
* Azure proxy configurations will be preferred over Java proxy configurations as they are more closely scoped to
* the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred.
*
* <p>
* {@code null} will be returned if no proxy was found in the environment.
*
* @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If
* {@code null} is passed then {@link Configuration
* @return A {@link ProxyOptions} reflecting a proxy loaded from the environment, if no proxy is found {@code null}
* will be returned.
*/
/**
* Attempts to load a proxy from the environment.
* <p>
* If a proxy is found and loaded, the proxy address is DNS resolved based on {@code createUnresolved}. When {@code
* createUnresolved} is true resolving {@link
* calls.
* <p>
* Environment configurations are loaded in this order:
* <ol>
* <li>Azure HTTPS</li>
* <li>Azure HTTP</li>
* <li>Java HTTPS</li>
* <li>Java HTTP</li>
* </ol>
*
* Azure proxy configurations will be preferred over Java proxy configurations as they are more closely scoped to
* the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred.
* <p>
* {@code null} will be returned if no proxy was found in the environment.
*
* @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If
* {@code null} is passed then {@link Configuration
* Configuration
* @param createUnresolved Flag determining whether the returned {@link ProxyOptions} is unresolved.
* @return A {@link ProxyOptions} reflecting a proxy loaded from the environment, if no proxy is found {@code null}
* will be returned.
*/
public static ProxyOptions fromConfiguration(Configuration configuration, boolean createUnresolved) {
Configuration proxyConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
return attemptToLoadProxy(proxyConfiguration, createUnresolved);
}
private static ProxyOptions attemptToLoadProxy(Configuration configuration, boolean createUnresolved) {
if (configuration == Configuration.NONE) {
return null;
}
ProxyOptions proxyOptions = null;
if (Boolean.parseBoolean(configuration.get(JAVA_SYSTEM_PROXY_PREREQUISITE))) {
proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTPS_PROXY);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from HTTPS_PROXY environment variable.");
return proxyOptions;
}
proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTP_PROXY);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from HTTP_PROXY environment variable.");
return proxyOptions;
}
}
proxyOptions = attemptToLoadAzureSdkProxy(configuration, createUnresolved);
if (proxyOptions != null) {
return proxyOptions;
}
proxyOptions = attemptToLoadJavaProxy(configuration, createUnresolved, HTTPS);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from JVM HTTPS system properties.");
return proxyOptions;
}
proxyOptions = attemptToLoadJavaProxy(configuration, createUnresolved, HTTP);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from JVM HTTP system properties.");
return proxyOptions;
}
return null;
}
private static ProxyOptions attemptToLoadSystemProxy(Configuration configuration, boolean createUnresolved,
String proxyProperty) {
String proxyConfiguration = configuration.get(proxyProperty);
if (CoreUtils.isNullOrEmpty(proxyConfiguration)) {
return null;
}
try {
URL proxyUrl = new URL(proxyConfiguration);
int port = (proxyUrl.getPort() == -1) ? proxyUrl.getDefaultPort() : proxyUrl.getPort();
InetSocketAddress socketAddress = (createUnresolved)
? InetSocketAddress.createUnresolved(proxyUrl.getHost(), port)
: new InetSocketAddress(proxyUrl.getHost(), port);
ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, socketAddress);
String nonProxyHostsString = configuration.get(Configuration.PROPERTY_NO_PROXY);
if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) {
proxyOptions.nonProxyHosts = sanitizeNoProxy(nonProxyHostsString);
LOGGER.log(LogLevel.VERBOSE, () -> "Using non-proxy host regex: " + proxyOptions.nonProxyHosts);
}
String userInfo = proxyUrl.getUserInfo();
if (userInfo != null) {
String[] usernamePassword = userInfo.split(":", 2);
if (usernamePassword.length == 2) {
try {
proxyOptions.setCredentials(
URLDecoder.decode(usernamePassword[0], StandardCharsets.UTF_8.toString()),
URLDecoder.decode(usernamePassword[1], StandardCharsets.UTF_8.toString())
);
} catch (UnsupportedEncodingException e) {
return null;
}
}
}
return proxyOptions;
} catch (MalformedURLException ex) {
LOGGER.warning(INVALID_AZURE_PROXY_URL, proxyProperty);
return null;
}
}
/*
* Helper function that sanitizes 'NO_PROXY' into a Pattern safe string.
*/
static String sanitizeNoProxy(String noProxyString) {
return sanitizeNonProxyHosts(NO_PROXY_SPLIT.split(noProxyString));
}
private static ProxyOptions attemptToLoadJavaProxy(Configuration configuration, boolean createUnresolved,
String type) {
String host = configuration.get(type + "." + JAVA_PROXY_HOST);
if (CoreUtils.isNullOrEmpty(host)) {
return null;
}
int port;
try {
port = Integer.parseInt(configuration.get(type + "." + JAVA_PROXY_PORT));
} catch (NumberFormatException ex) {
port = HTTPS.equals(type) ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT;
}
String nonProxyHostsString = configuration.get(JAVA_NON_PROXY_HOSTS);
String username = configuration.get(type + "." + JAVA_PROXY_USER);
String password = configuration.get(type + "." + JAVA_PROXY_PASSWORD);
return createOptions(host, port, nonProxyHostsString, username, password, createUnresolved);
}
private static ProxyOptions attemptToLoadAzureSdkProxy(Configuration configuration, boolean createUnresolved) {
String host = configuration.get(HOST_PROPERTY);
if (CoreUtils.isNullOrEmpty(host)) {
return null;
}
int port = configuration.get(PORT_PROPERTY);
String nonProxyHostsString = configuration.get(NON_PROXY_PROPERTY);
String username = configuration.get(USER_PROPERTY);
String password = configuration.get(PASSWORD_PROPERTY);
return createOptions(host, port, nonProxyHostsString, username, password, createUnresolved);
}
private static ProxyOptions createOptions(String host, int port, String nonProxyHostsString, String username, String password, boolean createUnresolved) {
InetSocketAddress socketAddress = (createUnresolved)
? InetSocketAddress.createUnresolved(host, port)
: new InetSocketAddress(host, port);
ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, socketAddress);
if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) {
proxyOptions.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHostsString);
LOGGER.log(LogLevel.VERBOSE, () -> "Using non-proxy host regex: " + proxyOptions.nonProxyHosts);
}
if (username != null && password != null) {
proxyOptions.setCredentials(username, password);
}
return proxyOptions;
}
/*
* Helper function that sanitizes 'http.nonProxyHosts' into a Pattern safe string.
*/
static String sanitizeJavaHttpNonProxyHosts(String nonProxyHostsString) {
return sanitizeNonProxyHosts(HTTP_NON_PROXY_HOSTS_SPLIT.split(nonProxyHostsString));
}
private static String sanitizeNonProxyHosts(String[] nonProxyHosts) {
StringBuilder sanitizedBuilder = new StringBuilder();
for (int i = 0; i < nonProxyHosts.length; i++) {
if (i > 0) {
sanitizedBuilder.append("|");
}
String prefixWildcard = "";
String suffixWildcard = "";
String sanitizedNonProxyHost = nonProxyHosts[i];
/*
* If the non-proxy host begins with either '.', '*', '.*', or any of the previous with a trailing '?'
* substring the non-proxy host and set the wildcard prefix.
*/
if (sanitizedNonProxyHost.startsWith(".")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1);
} else if (sanitizedNonProxyHost.startsWith(".?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
} else if (sanitizedNonProxyHost.startsWith("*?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
} else if (sanitizedNonProxyHost.startsWith("*")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1);
} else if (sanitizedNonProxyHost.startsWith(".*?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(3);
} else if (sanitizedNonProxyHost.startsWith(".*")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
}
/*
* Same with the ending of the non-proxy host, if it has a suffix wildcard trim the non-proxy host and
* retain the suffix wildcard.
*/
if (sanitizedNonProxyHost.endsWith(".")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2);
} else if (sanitizedNonProxyHost.endsWith(".?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
} else if (sanitizedNonProxyHost.endsWith("*?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
} else if (sanitizedNonProxyHost.endsWith("*")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2);
} else if (sanitizedNonProxyHost.endsWith(".*?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 4);
} else if (sanitizedNonProxyHost.endsWith(".*")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
}
try {
String attemptToSanitizeAsRegex = sanitizedNonProxyHost;
attemptToSanitizeAsRegex = UNESCAPED_PERIOD.matcher(attemptToSanitizeAsRegex).replaceAll("\\\\.");
attemptToSanitizeAsRegex = ANY.matcher(attemptToSanitizeAsRegex).replaceAll("\\.*?");
sanitizedNonProxyHost = Pattern.compile(attemptToSanitizeAsRegex).pattern();
} catch (PatternSyntaxException ex) {
/*
* Replace the non-proxy host with the sanitized value.
*
* The body of the non-proxy host is quoted to handle scenarios such a '127.0.0.1' or '*.azure.com'
* where without quoting the '.' in the string would be treated as the match any character instead of
* the literal '.' character.
*/
sanitizedNonProxyHost = Pattern.quote(sanitizedNonProxyHost);
}
sanitizedBuilder.append("(")
.append(prefixWildcard)
.append(sanitizedNonProxyHost)
.append(suffixWildcard)
.append(")");
}
return sanitizedBuilder.toString();
}
/**
* The type of the proxy.
*/
public enum Type {
/**
* HTTP proxy type.
*/
HTTP(Proxy.Type.HTTP),
/**
* SOCKS4 proxy type.
*/
SOCKS4(Proxy.Type.SOCKS),
/**
* SOCKS5 proxy type.
*/
SOCKS5(Proxy.Type.SOCKS);
private final Proxy.Type proxyType;
Type(Proxy.Type proxyType) {
this.proxyType = proxyType;
}
/**
* Get the {@link Proxy.Type} equivalent of this type.
*
* @return the proxy type
*/
public Proxy.Type toProxyType() {
return proxyType;
}
}
/**
* Lists available configuration property names for HTTP {@link ProxyOptions}.
*/
private static class ConfigurationProperties {
/**
* Represents a list of hosts that should be reached directly, bypassing the proxy.
* This is a list of patterns separated by '|'. The patterns may start or end with a '*' for wildcards.
* Any host matching one of these patterns will be reached through a direct connection instead of through a proxy.
* <p>
* Default value is {@code null}
*/
public static final String HTTP_PROXY_NON_PROXY_HOSTS = "http.proxy.non-proxy-hosts";
/**
* The HTTP host name of the proxy server.
* <p>
* Default value is {@code null}.
*/
public static final String HTTP_PROXY_HOST = "http.proxy.hostname";
/**
* The port number of the proxy server.
* <p>
* Default value is {@code 443}.
*/
public static final String HTTP_PROXY_PORT = "http.proxy.port";
/**
* The HTTP proxy server user.
* Default value is {@code null}.
*/
public static final String HTTP_PROXY_USER = "http.proxy.username";
/**
* The HTTP proxy server password.
* Default value is {@code null}.
*/
public static final String HTTP_PROXY_PASSWORD = "http.proxy.password";
}
} |
I'm trying to recall why `Context.NONE` throws instead of returning a null proxy but I can't remember why, and I agree this behavior seems odd. I wonder if we can change this to return null instead without any major consequences. | public static ProxyOptions fromConfiguration(Configuration configuration) {
if (configuration == Configuration.NONE) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException(INVALID_CONFIGURATION_MESSAGE));
}
Configuration proxyConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
boolean createUnresolved = proxyConfiguration.get(Properties.CREATE_UNRESOLVED);
return attemptToLoadProxy(proxyConfiguration, createUnresolved);
} | if (configuration == Configuration.NONE) { | public static ProxyOptions fromConfiguration(Configuration configuration) {
return fromConfiguration(configuration, false);
} | class ProxyOptions {
private static final ClientLogger LOGGER = new ClientLogger(ProxyOptions.class);
private static final String INVALID_CONFIGURATION_MESSAGE = "'configuration' cannot be 'Configuration.NONE'.";
private static final String INVALID_AZURE_PROXY_URL = "Configuration {} is an invalid URL and is being ignored.";
/*
* This indicates whether system proxy configurations (HTTPS_PROXY, HTTP_PROXY) are allowed to be used.
*/
private static final String JAVA_SYSTEM_PROXY_PREREQUISITE = "java.net.useSystemProxies";
private static final int DEFAULT_HTTPS_PORT = 443;
private static final int DEFAULT_HTTP_PORT = 80;
/*
* The 'http.nonProxyHosts' system property is expected to be delimited by '|', but don't split escaped '|'s.
*/
private static final Pattern HTTP_NON_PROXY_HOSTS_SPLIT = Pattern.compile("(?<!\\\\)\\|");
/*
* The 'NO_PROXY' environment variable is expected to be delimited by ',', but don't split escaped ','s.
*/
private static final Pattern NO_PROXY_SPLIT = Pattern.compile("(?<!\\\\),");
private static final Pattern UNESCAPED_PERIOD = Pattern.compile("(?<!\\\\)\\.");
private static final Pattern ANY = Pattern.compile("\\*");
private final InetSocketAddress address;
private final Type type;
private String username;
private String password;
private String nonProxyHosts;
/**
* Creates ProxyOptions.
*
* @param type the proxy type
* @param address the proxy address (ip and port number)
*/
public ProxyOptions(Type type, InetSocketAddress address) {
this.type = type;
this.address = address;
}
/**
* Set the proxy credentials.
*
* @param username proxy user name
* @param password proxy password
* @return the updated ProxyOptions object
*/
public ProxyOptions setCredentials(String username, String password) {
this.username = Objects.requireNonNull(username, "'username' cannot be null.");
this.password = Objects.requireNonNull(password, "'password' cannot be null.");
return this;
}
/**
* Sets the hosts which bypass the proxy.
* <p>
* The expected format of the passed string is a {@code '|'} delimited list of hosts which should bypass the proxy.
* Individual host strings may contain regex characters such as {@code '*'}.
*
* @param nonProxyHosts Hosts that bypass the proxy.
* @return the updated ProxyOptions object
*/
public ProxyOptions setNonProxyHosts(String nonProxyHosts) {
this.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHosts);
return this;
}
/**
* @return the address of the proxy.
*/
public InetSocketAddress getAddress() {
return address;
}
/**
* @return the type of the proxy.
*/
public Type getType() {
return type;
}
/**
* @return the proxy user name.
*/
public String getUsername() {
return this.username;
}
/**
* @return the proxy password.
*/
public String getPassword() {
return this.password;
}
/**
* @return the hosts that bypass the proxy.
*/
public String getNonProxyHosts() {
return this.nonProxyHosts;
}
/**
* Attempts to load a proxy from the environment.
* <p>
* If a proxy is found and loaded the proxy address is DNS resolved.
* <p>
* Environment configurations are loaded in this order:
* <ol>
* <li>Azure HTTPS</li>
* <li>Azure HTTP</li>
* <li>Java HTTPS</li>
* <li>Java HTTP</li>
* </ol>
*
* Azure proxy configurations will be preferred over Java proxy configurations as they are more closely scoped to
* the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred.
*
* <p>
* {@code null} will be returned if no proxy was found in the environment.
*
* @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If
* {@code null} is passed then {@link Configuration
* Configuration
* @return A {@link ProxyOptions} reflecting a proxy loaded from the environment, if no proxy is found {@code null}
* will be returned.
* @throws IllegalArgumentException If {@code configuration} is {@link Configuration
*/
/**
* Attempts to load a proxy from the environment.
* <p>
* If a proxy is found and loaded, the proxy address is DNS resolved based on {@code createUnresolved}. When {@code
* createUnresolved} is true resolving {@link
* calls.
* <p>
* Environment configurations are loaded in this order:
* <ol>
* <li>Azure HTTPS</li>
* <li>Azure HTTP</li>
* <li>Java HTTPS</li>
* <li>Java HTTP</li>
* </ol>
*
* Azure proxy configurations will be preferred over Java proxy configurations as they are more closely scoped to
* the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred.
* <p>
* {@code null} will be returned if no proxy was found in the environment.
*
* @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If
* {@code null} is passed then {@link Configuration
* Configuration
* @param createUnresolved Flag determining whether the returned {@link ProxyOptions} is unresolved.
* @return A {@link ProxyOptions} reflecting a proxy loaded from the environment, if no proxy is found {@code null}
* will be returned.
* @throws IllegalArgumentException If {@code configuration} is {@link Configuration
*/
public static ProxyOptions fromConfiguration(Configuration configuration, boolean createUnresolved) {
if (configuration == Configuration.NONE) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException(INVALID_CONFIGURATION_MESSAGE));
}
Configuration proxyConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
return attemptToLoadProxy(proxyConfiguration, createUnresolved);
}
private static ProxyOptions attemptToLoadProxy(Configuration configuration, boolean createUnresolved) {
ProxyOptions proxyOptions;
if (Boolean.parseBoolean(configuration.get(JAVA_SYSTEM_PROXY_PREREQUISITE))) {
proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTPS_PROXY);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from HTTPS_PROXY environment variable.");
return proxyOptions;
}
proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTP_PROXY);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from HTTP_PROXY environment variable.");
return proxyOptions;
}
}
proxyOptions = attemptToLoadJavaProxy(configuration, createUnresolved,
Properties.HTTPS_PROXY_HOST, Properties.HTTPS_PROXY_PORT, Properties.HTTPS_PROXY_USER, Properties.HTTPS_PROXY_PASSWORD, DEFAULT_HTTPS_PORT);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from JVM HTTPS system properties.");
return proxyOptions;
}
proxyOptions = attemptToLoadJavaProxy(configuration, createUnresolved,
Properties.HTTP_PROXY_HOST, Properties.HTTP_PROXY_PORT, Properties.HTTP_PROXY_USER, Properties.HTTP_PROXY_PASSWORD, DEFAULT_HTTP_PORT);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from JVM HTTP system properties.");
return proxyOptions;
}
return null;
}
private static ProxyOptions attemptToLoadSystemProxy(Configuration configuration, boolean createUnresolved,
String proxyProperty) {
String proxyConfiguration = configuration.get(proxyProperty);
if (CoreUtils.isNullOrEmpty(proxyConfiguration)) {
return null;
}
try {
URL proxyUrl = new URL(proxyConfiguration);
int port = (proxyUrl.getPort() == -1) ? proxyUrl.getDefaultPort() : proxyUrl.getPort();
InetSocketAddress socketAddress = (createUnresolved)
? InetSocketAddress.createUnresolved(proxyUrl.getHost(), port)
: new InetSocketAddress(proxyUrl.getHost(), port);
ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, socketAddress);
String nonProxyHostsString = configuration.get(Configuration.PROPERTY_NO_PROXY);
if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) {
proxyOptions.nonProxyHosts = sanitizeNoProxy(nonProxyHostsString);
LOGGER.log(LogLevel.VERBOSE, () -> "Using non-proxy host regex: " + proxyOptions.nonProxyHosts);
}
String userInfo = proxyUrl.getUserInfo();
if (userInfo != null) {
String[] usernamePassword = userInfo.split(":", 2);
if (usernamePassword.length == 2) {
try {
proxyOptions.setCredentials(
URLDecoder.decode(usernamePassword[0], StandardCharsets.UTF_8.toString()),
URLDecoder.decode(usernamePassword[1], StandardCharsets.UTF_8.toString())
);
} catch (UnsupportedEncodingException e) {
return null;
}
}
}
return proxyOptions;
} catch (MalformedURLException ex) {
LOGGER.warning(INVALID_AZURE_PROXY_URL, proxyProperty);
return null;
}
}
/*
* Helper function that sanitizes 'NO_PROXY' into a Pattern safe string.
*/
static String sanitizeNoProxy(String noProxyString) {
return sanitizeNonProxyHosts(NO_PROXY_SPLIT.split(noProxyString));
}
private static ProxyOptions attemptToLoadJavaProxy(Configuration configuration, boolean createUnresolved,
ConfigurationProperty<String> hostProperty,
ConfigurationProperty<Integer> portProperty,
ConfigurationProperty<String> userProperty,
ConfigurationProperty<String> passwordProperty,
Integer defaultPort) {
String host = configuration.get(hostProperty);
if (CoreUtils.isNullOrEmpty(host)) {
return null;
}
int port;
try {
port = configuration.get(portProperty);
} catch (NumberFormatException ex) {
port = defaultPort;
}
InetSocketAddress socketAddress = (createUnresolved)
? InetSocketAddress.createUnresolved(host, port)
: new InetSocketAddress(host, port);
ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, socketAddress);
String nonProxyHostsString = configuration.get(Properties.NO_PROXY);
if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) {
proxyOptions.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHostsString);
LOGGER.log(LogLevel.VERBOSE, () -> "Using non-proxy host regex: " + proxyOptions.nonProxyHosts);
}
String username = configuration.get(userProperty);
String password = configuration.get(passwordProperty);
if (username != null && password != null) {
proxyOptions.setCredentials(username, password);
}
return proxyOptions;
}
/*
* Helper function that sanitizes 'http.nonProxyHosts' into a Pattern safe string.
*/
static String sanitizeJavaHttpNonProxyHosts(String nonProxyHostsString) {
return sanitizeNonProxyHosts(HTTP_NON_PROXY_HOSTS_SPLIT.split(nonProxyHostsString));
}
private static String sanitizeNonProxyHosts(String[] nonProxyHosts) {
StringBuilder sanitizedBuilder = new StringBuilder();
for (int i = 0; i < nonProxyHosts.length; i++) {
if (i > 0) {
sanitizedBuilder.append("|");
}
String prefixWildcard = "";
String suffixWildcard = "";
String sanitizedNonProxyHost = nonProxyHosts[i];
/*
* If the non-proxy host begins with either '.', '*', '.*', or any of the previous with a trailing '?'
* substring the non-proxy host and set the wildcard prefix.
*/
if (sanitizedNonProxyHost.startsWith(".")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1);
} else if (sanitizedNonProxyHost.startsWith(".?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
} else if (sanitizedNonProxyHost.startsWith("*?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
} else if (sanitizedNonProxyHost.startsWith("*")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1);
} else if (sanitizedNonProxyHost.startsWith(".*?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(3);
} else if (sanitizedNonProxyHost.startsWith(".*")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
}
/*
* Same with the ending of the non-proxy host, if it has a suffix wildcard trim the non-proxy host and
* retain the suffix wildcard.
*/
if (sanitizedNonProxyHost.endsWith(".")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2);
} else if (sanitizedNonProxyHost.endsWith(".?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
} else if (sanitizedNonProxyHost.endsWith("*?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
} else if (sanitizedNonProxyHost.endsWith("*")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2);
} else if (sanitizedNonProxyHost.endsWith(".*?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 4);
} else if (sanitizedNonProxyHost.endsWith(".*")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
}
try {
String attemptToSanitizeAsRegex = sanitizedNonProxyHost;
attemptToSanitizeAsRegex = UNESCAPED_PERIOD.matcher(attemptToSanitizeAsRegex).replaceAll("\\\\.");
attemptToSanitizeAsRegex = ANY.matcher(attemptToSanitizeAsRegex).replaceAll("\\.*?");
sanitizedNonProxyHost = Pattern.compile(attemptToSanitizeAsRegex).pattern();
} catch (PatternSyntaxException ex) {
/*
* Replace the non-proxy host with the sanitized value.
*
* The body of the non-proxy host is quoted to handle scenarios such a '127.0.0.1' or '*.azure.com'
* where without quoting the '.' in the string would be treated as the match any character instead of
* the literal '.' character.
*/
sanitizedNonProxyHost = Pattern.quote(sanitizedNonProxyHost);
}
sanitizedBuilder.append("(")
.append(prefixWildcard)
.append(sanitizedNonProxyHost)
.append(suffixWildcard)
.append(")");
}
return sanitizedBuilder.toString();
}
/**
* The type of the proxy.
*/
public enum Type {
/**
* HTTP proxy type.
*/
HTTP(Proxy.Type.HTTP),
/**
* SOCKS4 proxy type.
*/
SOCKS4(Proxy.Type.SOCKS),
/**
* SOCKS5 proxy type.
*/
SOCKS5(Proxy.Type.SOCKS);
private final Proxy.Type proxyType;
Type(Proxy.Type proxyType) {
this.proxyType = proxyType;
}
/**
* Get the {@link Proxy.Type} equivalent of this type.
*
* @return the proxy type
*/
public Proxy.Type toProxyType() {
return proxyType;
}
}
private static class Properties {
public static final ConfigurationProperty<String> NO_PROXY = ConfigurationProperty.stringPropertyBuilder("http.proxy.non-proxy-hosts")
.environmentAliases("http.nonProxyHosts", Configuration.PROPERTY_NO_PROXY)
.canLogValue(true)
.build();
public static final ConfigurationProperty<Boolean> CREATE_UNRESOLVED = ConfigurationUtils.booleanSharedPropertyBuilder("http.proxy.create-unresolved")
.defaultValue(false)
.build();
public static final ConfigurationProperty<String> HTTP_PROXY_HOST = ConfigurationUtils.stringSharedPropertyBuilder("http.proxy.host")
.environmentAliases("http.proxyHost")
.canLogValue(true)
.build();
public static final ConfigurationProperty<Integer> HTTP_PROXY_PORT = ConfigurationUtils.integerSharedPropertyBuilder("http.proxy.port")
.environmentAliases("http.proxyPort")
.defaultValue(DEFAULT_HTTP_PORT)
.build();
public static final ConfigurationProperty<String> HTTP_PROXY_USER = ConfigurationUtils.stringSharedPropertyBuilder("http.proxy.username")
.environmentAliases("http.proxyUser")
.build();
public static final ConfigurationProperty<String> HTTP_PROXY_PASSWORD = ConfigurationUtils.stringSharedPropertyBuilder("http.proxy.password")
.environmentAliases("http.proxyPassword")
.build();
public static final ConfigurationProperty<String> HTTPS_PROXY_HOST = ConfigurationUtils.stringSharedPropertyBuilder("https.proxy.host")
.environmentAliases("https.proxyHost")
.canLogValue(true)
.build();
public static final ConfigurationProperty<Integer> HTTPS_PROXY_PORT = ConfigurationUtils.integerSharedPropertyBuilder("https.proxy.port")
.environmentAliases("https.proxyPort")
.defaultValue(DEFAULT_HTTPS_PORT)
.build();
public static final ConfigurationProperty<String> HTTPS_PROXY_USER = ConfigurationUtils.stringSharedPropertyBuilder("https.proxy.username")
.environmentAliases("https.proxyUser")
.build();
public static final ConfigurationProperty<String> HTTPS_PROXY_PASSWORD = ConfigurationUtils.stringSharedPropertyBuilder("https.proxy.password")
.environmentAliases("https.proxyPassword")
.build();
}
} | class ProxyOptions {
private static final ClientLogger LOGGER = new ClientLogger(ProxyOptions.class);
private static final String INVALID_AZURE_PROXY_URL = "Configuration {} is an invalid URL and is being ignored.";
/*
* This indicates whether system proxy configurations (HTTPS_PROXY, HTTP_PROXY) are allowed to be used.
*/
private static final String JAVA_SYSTEM_PROXY_PREREQUISITE = "java.net.useSystemProxies";
/*
* Java environment variables related to proxies. The protocol is removed since these are the same for 'https' and
* 'http', the exception is 'http.nonProxyHosts' as it is used for both.
*/
private static final String JAVA_PROXY_HOST = "proxyHost";
private static final String JAVA_PROXY_PORT = "proxyPort";
private static final String JAVA_PROXY_USER = "proxyUser";
private static final String JAVA_PROXY_PASSWORD = "proxyPassword";
private static final String JAVA_NON_PROXY_HOSTS = "http.nonProxyHosts";
private static final String HTTPS = "https";
private static final int DEFAULT_HTTPS_PORT = 443;
private static final String HTTP = "http";
private static final int DEFAULT_HTTP_PORT = 80;
/*
* The 'http.nonProxyHosts' system property is expected to be delimited by '|', but don't split escaped '|'s.
*/
private static final Pattern HTTP_NON_PROXY_HOSTS_SPLIT = Pattern.compile("(?<!\\\\)\\|");
/*
* The 'NO_PROXY' environment variable is expected to be delimited by ',', but don't split escaped ','s.
*/
private static final Pattern NO_PROXY_SPLIT = Pattern.compile("(?<!\\\\),");
private static final Pattern UNESCAPED_PERIOD = Pattern.compile("(?<!\\\\)\\.");
private static final Pattern ANY = Pattern.compile("\\*");
private static final ConfigurationProperty<String> NON_PROXY_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_NON_PROXY_HOSTS)
.shared(true)
.logValue(true)
.build();
private static final ConfigurationProperty<String> HOST_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_HOST)
.shared(true)
.logValue(true)
.build();
private static final ConfigurationProperty<Integer> PORT_PROPERTY = ConfigurationPropertyBuilder.ofInteger(ConfigurationProperties.HTTP_PROXY_PORT)
.shared(true)
.defaultValue(DEFAULT_HTTPS_PORT)
.build();
private static final ConfigurationProperty<String> USER_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_USER)
.shared(true)
.logValue(true)
.build();
private static final ConfigurationProperty<String> PASSWORD_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_PASSWORD)
.shared(true)
.build();
private final InetSocketAddress address;
private final Type type;
private String username;
private String password;
private String nonProxyHosts;
/**
* Creates ProxyOptions.
*
* @param type the proxy type
* @param address the proxy address (ip and port number)
*/
public ProxyOptions(Type type, InetSocketAddress address) {
this.type = type;
this.address = address;
}
/**
* Set the proxy credentials.
*
* @param username proxy user name
* @param password proxy password
* @return the updated ProxyOptions object
*/
public ProxyOptions setCredentials(String username, String password) {
this.username = Objects.requireNonNull(username, "'username' cannot be null.");
this.password = Objects.requireNonNull(password, "'password' cannot be null.");
return this;
}
/**
* Sets the hosts which bypass the proxy.
* <p>
* The expected format of the passed string is a {@code '|'} delimited list of hosts which should bypass the proxy.
* Individual host strings may contain regex characters such as {@code '*'}.
*
* @param nonProxyHosts Hosts that bypass the proxy.
* @return the updated ProxyOptions object
*/
public ProxyOptions setNonProxyHosts(String nonProxyHosts) {
this.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHosts);
return this;
}
/**
* @return the address of the proxy.
*/
public InetSocketAddress getAddress() {
return address;
}
/**
* @return the type of the proxy.
*/
public Type getType() {
return type;
}
/**
* @return the proxy user name.
*/
public String getUsername() {
return this.username;
}
/**
* @return the proxy password.
*/
public String getPassword() {
return this.password;
}
/**
* @return the hosts that bypass the proxy.
*/
public String getNonProxyHosts() {
return this.nonProxyHosts;
}
/**
* Attempts to load a proxy from the configuration.
* <p>
* If a proxy is found and loaded the proxy address is DNS resolved.
* <p>
* Environment configurations are loaded in this order:
* <ol>
* <li>Azure HTTPS</li>
* <li>Azure HTTP</li>
* <li>Java HTTPS</li>
* <li>Java HTTP</li>
* </ol>
*
* Azure proxy configurations will be preferred over Java proxy configurations as they are more closely scoped to
* the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred.
*
* <p>
* {@code null} will be returned if no proxy was found in the environment.
*
* @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If
* {@code null} is passed then {@link Configuration
* @return A {@link ProxyOptions} reflecting a proxy loaded from the environment, if no proxy is found {@code null}
* will be returned.
*/
/**
* Attempts to load a proxy from the environment.
* <p>
* If a proxy is found and loaded, the proxy address is DNS resolved based on {@code createUnresolved}. When {@code
* createUnresolved} is true resolving {@link
* calls.
* <p>
* Environment configurations are loaded in this order:
* <ol>
* <li>Azure HTTPS</li>
* <li>Azure HTTP</li>
* <li>Java HTTPS</li>
* <li>Java HTTP</li>
* </ol>
*
* Azure proxy configurations will be preferred over Java proxy configurations as they are more closely scoped to
* the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred.
* <p>
* {@code null} will be returned if no proxy was found in the environment.
*
* @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If
* {@code null} is passed then {@link Configuration
* Configuration
* @param createUnresolved Flag determining whether the returned {@link ProxyOptions} is unresolved.
* @return A {@link ProxyOptions} reflecting a proxy loaded from the environment, if no proxy is found {@code null}
* will be returned.
*/
public static ProxyOptions fromConfiguration(Configuration configuration, boolean createUnresolved) {
Configuration proxyConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
return attemptToLoadProxy(proxyConfiguration, createUnresolved);
}
private static ProxyOptions attemptToLoadProxy(Configuration configuration, boolean createUnresolved) {
if (configuration == Configuration.NONE) {
return null;
}
ProxyOptions proxyOptions = null;
if (Boolean.parseBoolean(configuration.get(JAVA_SYSTEM_PROXY_PREREQUISITE))) {
proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTPS_PROXY);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from HTTPS_PROXY environment variable.");
return proxyOptions;
}
proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTP_PROXY);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from HTTP_PROXY environment variable.");
return proxyOptions;
}
}
proxyOptions = attemptToLoadAzureSdkProxy(configuration, createUnresolved);
if (proxyOptions != null) {
return proxyOptions;
}
proxyOptions = attemptToLoadJavaProxy(configuration, createUnresolved, HTTPS);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from JVM HTTPS system properties.");
return proxyOptions;
}
proxyOptions = attemptToLoadJavaProxy(configuration, createUnresolved, HTTP);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from JVM HTTP system properties.");
return proxyOptions;
}
return null;
}
private static ProxyOptions attemptToLoadSystemProxy(Configuration configuration, boolean createUnresolved,
String proxyProperty) {
String proxyConfiguration = configuration.get(proxyProperty);
if (CoreUtils.isNullOrEmpty(proxyConfiguration)) {
return null;
}
try {
URL proxyUrl = new URL(proxyConfiguration);
int port = (proxyUrl.getPort() == -1) ? proxyUrl.getDefaultPort() : proxyUrl.getPort();
InetSocketAddress socketAddress = (createUnresolved)
? InetSocketAddress.createUnresolved(proxyUrl.getHost(), port)
: new InetSocketAddress(proxyUrl.getHost(), port);
ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, socketAddress);
String nonProxyHostsString = configuration.get(Configuration.PROPERTY_NO_PROXY);
if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) {
proxyOptions.nonProxyHosts = sanitizeNoProxy(nonProxyHostsString);
LOGGER.log(LogLevel.VERBOSE, () -> "Using non-proxy host regex: " + proxyOptions.nonProxyHosts);
}
String userInfo = proxyUrl.getUserInfo();
if (userInfo != null) {
String[] usernamePassword = userInfo.split(":", 2);
if (usernamePassword.length == 2) {
try {
proxyOptions.setCredentials(
URLDecoder.decode(usernamePassword[0], StandardCharsets.UTF_8.toString()),
URLDecoder.decode(usernamePassword[1], StandardCharsets.UTF_8.toString())
);
} catch (UnsupportedEncodingException e) {
return null;
}
}
}
return proxyOptions;
} catch (MalformedURLException ex) {
LOGGER.warning(INVALID_AZURE_PROXY_URL, proxyProperty);
return null;
}
}
/*
* Helper function that sanitizes 'NO_PROXY' into a Pattern safe string.
*/
static String sanitizeNoProxy(String noProxyString) {
return sanitizeNonProxyHosts(NO_PROXY_SPLIT.split(noProxyString));
}
private static ProxyOptions attemptToLoadJavaProxy(Configuration configuration, boolean createUnresolved,
String type) {
String host = configuration.get(type + "." + JAVA_PROXY_HOST);
if (CoreUtils.isNullOrEmpty(host)) {
return null;
}
int port;
try {
port = Integer.parseInt(configuration.get(type + "." + JAVA_PROXY_PORT));
} catch (NumberFormatException ex) {
port = HTTPS.equals(type) ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT;
}
String nonProxyHostsString = configuration.get(JAVA_NON_PROXY_HOSTS);
String username = configuration.get(type + "." + JAVA_PROXY_USER);
String password = configuration.get(type + "." + JAVA_PROXY_PASSWORD);
return createOptions(host, port, nonProxyHostsString, username, password, createUnresolved);
}
private static ProxyOptions attemptToLoadAzureSdkProxy(Configuration configuration, boolean createUnresolved) {
String host = configuration.get(HOST_PROPERTY);
if (CoreUtils.isNullOrEmpty(host)) {
return null;
}
int port = configuration.get(PORT_PROPERTY);
String nonProxyHostsString = configuration.get(NON_PROXY_PROPERTY);
String username = configuration.get(USER_PROPERTY);
String password = configuration.get(PASSWORD_PROPERTY);
return createOptions(host, port, nonProxyHostsString, username, password, createUnresolved);
}
private static ProxyOptions createOptions(String host, int port, String nonProxyHostsString, String username, String password, boolean createUnresolved) {
InetSocketAddress socketAddress = (createUnresolved)
? InetSocketAddress.createUnresolved(host, port)
: new InetSocketAddress(host, port);
ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, socketAddress);
if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) {
proxyOptions.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHostsString);
LOGGER.log(LogLevel.VERBOSE, () -> "Using non-proxy host regex: " + proxyOptions.nonProxyHosts);
}
if (username != null && password != null) {
proxyOptions.setCredentials(username, password);
}
return proxyOptions;
}
/*
* Helper function that sanitizes 'http.nonProxyHosts' into a Pattern safe string.
*/
static String sanitizeJavaHttpNonProxyHosts(String nonProxyHostsString) {
return sanitizeNonProxyHosts(HTTP_NON_PROXY_HOSTS_SPLIT.split(nonProxyHostsString));
}
private static String sanitizeNonProxyHosts(String[] nonProxyHosts) {
StringBuilder sanitizedBuilder = new StringBuilder();
for (int i = 0; i < nonProxyHosts.length; i++) {
if (i > 0) {
sanitizedBuilder.append("|");
}
String prefixWildcard = "";
String suffixWildcard = "";
String sanitizedNonProxyHost = nonProxyHosts[i];
/*
* If the non-proxy host begins with either '.', '*', '.*', or any of the previous with a trailing '?'
* substring the non-proxy host and set the wildcard prefix.
*/
if (sanitizedNonProxyHost.startsWith(".")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1);
} else if (sanitizedNonProxyHost.startsWith(".?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
} else if (sanitizedNonProxyHost.startsWith("*?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
} else if (sanitizedNonProxyHost.startsWith("*")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1);
} else if (sanitizedNonProxyHost.startsWith(".*?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(3);
} else if (sanitizedNonProxyHost.startsWith(".*")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
}
/*
* Same with the ending of the non-proxy host, if it has a suffix wildcard trim the non-proxy host and
* retain the suffix wildcard.
*/
if (sanitizedNonProxyHost.endsWith(".")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2);
} else if (sanitizedNonProxyHost.endsWith(".?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
} else if (sanitizedNonProxyHost.endsWith("*?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
} else if (sanitizedNonProxyHost.endsWith("*")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2);
} else if (sanitizedNonProxyHost.endsWith(".*?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 4);
} else if (sanitizedNonProxyHost.endsWith(".*")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
}
try {
String attemptToSanitizeAsRegex = sanitizedNonProxyHost;
attemptToSanitizeAsRegex = UNESCAPED_PERIOD.matcher(attemptToSanitizeAsRegex).replaceAll("\\\\.");
attemptToSanitizeAsRegex = ANY.matcher(attemptToSanitizeAsRegex).replaceAll("\\.*?");
sanitizedNonProxyHost = Pattern.compile(attemptToSanitizeAsRegex).pattern();
} catch (PatternSyntaxException ex) {
/*
* Replace the non-proxy host with the sanitized value.
*
* The body of the non-proxy host is quoted to handle scenarios such a '127.0.0.1' or '*.azure.com'
* where without quoting the '.' in the string would be treated as the match any character instead of
* the literal '.' character.
*/
sanitizedNonProxyHost = Pattern.quote(sanitizedNonProxyHost);
}
sanitizedBuilder.append("(")
.append(prefixWildcard)
.append(sanitizedNonProxyHost)
.append(suffixWildcard)
.append(")");
}
return sanitizedBuilder.toString();
}
/**
* The type of the proxy.
*/
public enum Type {
/**
* HTTP proxy type.
*/
HTTP(Proxy.Type.HTTP),
/**
* SOCKS4 proxy type.
*/
SOCKS4(Proxy.Type.SOCKS),
/**
* SOCKS5 proxy type.
*/
SOCKS5(Proxy.Type.SOCKS);
private final Proxy.Type proxyType;
Type(Proxy.Type proxyType) {
this.proxyType = proxyType;
}
/**
* Get the {@link Proxy.Type} equivalent of this type.
*
* @return the proxy type
*/
public Proxy.Type toProxyType() {
return proxyType;
}
}
/**
* Lists available configuration property names for HTTP {@link ProxyOptions}.
*/
private static class ConfigurationProperties {
/**
* Represents a list of hosts that should be reached directly, bypassing the proxy.
* This is a list of patterns separated by '|'. The patterns may start or end with a '*' for wildcards.
* Any host matching one of these patterns will be reached through a direct connection instead of through a proxy.
* <p>
* Default value is {@code null}
*/
public static final String HTTP_PROXY_NON_PROXY_HOSTS = "http.proxy.non-proxy-hosts";
/**
* The HTTP host name of the proxy server.
* <p>
* Default value is {@code null}.
*/
public static final String HTTP_PROXY_HOST = "http.proxy.hostname";
/**
* The port number of the proxy server.
* <p>
* Default value is {@code 443}.
*/
public static final String HTTP_PROXY_PORT = "http.proxy.port";
/**
* The HTTP proxy server user.
* Default value is {@code null}.
*/
public static final String HTTP_PROXY_USER = "http.proxy.username";
/**
* The HTTP proxy server password.
* Default value is {@code null}.
*/
public static final String HTTP_PROXY_PASSWORD = "http.proxy.password";
}
} |
The difference between `NONE` and `null` configuration I realized: - `NONE` is just an empty config and should always lead to `null` outcome - `null` configuration means implicit (enviroment) configuration I believe it's not breaking to return `null` instead of throwing: - The underlying method `attemptToLoadProxy` returns `null` when no proxy configuration is found, i.e. callers should expect to get `null` - stop throwing an exception is usually considered non-breaking. It's hard to imagine a case where someone relies on this exception being thrown I.e. for `ProxyOptions`, it's not breaking to remove the exception and we don't use it in other places in azure-core. This is also consistent with what we (in general) do in client libraries: https://github.com/Azure/azure-sdk-for-java/blob/b131f86920a386fd7191da6025b2901ffb6c4bfa/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClientBuilder.java#L456-L465 | public static ProxyOptions fromConfiguration(Configuration configuration) {
if (configuration == Configuration.NONE) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException(INVALID_CONFIGURATION_MESSAGE));
}
Configuration proxyConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
boolean createUnresolved = proxyConfiguration.get(Properties.CREATE_UNRESOLVED);
return attemptToLoadProxy(proxyConfiguration, createUnresolved);
} | if (configuration == Configuration.NONE) { | public static ProxyOptions fromConfiguration(Configuration configuration) {
return fromConfiguration(configuration, false);
} | class ProxyOptions {
private static final ClientLogger LOGGER = new ClientLogger(ProxyOptions.class);
private static final String INVALID_CONFIGURATION_MESSAGE = "'configuration' cannot be 'Configuration.NONE'.";
private static final String INVALID_AZURE_PROXY_URL = "Configuration {} is an invalid URL and is being ignored.";
/*
* This indicates whether system proxy configurations (HTTPS_PROXY, HTTP_PROXY) are allowed to be used.
*/
private static final String JAVA_SYSTEM_PROXY_PREREQUISITE = "java.net.useSystemProxies";
private static final int DEFAULT_HTTPS_PORT = 443;
private static final int DEFAULT_HTTP_PORT = 80;
/*
* The 'http.nonProxyHosts' system property is expected to be delimited by '|', but don't split escaped '|'s.
*/
private static final Pattern HTTP_NON_PROXY_HOSTS_SPLIT = Pattern.compile("(?<!\\\\)\\|");
/*
* The 'NO_PROXY' environment variable is expected to be delimited by ',', but don't split escaped ','s.
*/
private static final Pattern NO_PROXY_SPLIT = Pattern.compile("(?<!\\\\),");
private static final Pattern UNESCAPED_PERIOD = Pattern.compile("(?<!\\\\)\\.");
private static final Pattern ANY = Pattern.compile("\\*");
private final InetSocketAddress address;
private final Type type;
private String username;
private String password;
private String nonProxyHosts;
/**
* Creates ProxyOptions.
*
* @param type the proxy type
* @param address the proxy address (ip and port number)
*/
public ProxyOptions(Type type, InetSocketAddress address) {
this.type = type;
this.address = address;
}
/**
* Set the proxy credentials.
*
* @param username proxy user name
* @param password proxy password
* @return the updated ProxyOptions object
*/
public ProxyOptions setCredentials(String username, String password) {
this.username = Objects.requireNonNull(username, "'username' cannot be null.");
this.password = Objects.requireNonNull(password, "'password' cannot be null.");
return this;
}
/**
* Sets the hosts which bypass the proxy.
* <p>
* The expected format of the passed string is a {@code '|'} delimited list of hosts which should bypass the proxy.
* Individual host strings may contain regex characters such as {@code '*'}.
*
* @param nonProxyHosts Hosts that bypass the proxy.
* @return the updated ProxyOptions object
*/
public ProxyOptions setNonProxyHosts(String nonProxyHosts) {
this.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHosts);
return this;
}
/**
* @return the address of the proxy.
*/
public InetSocketAddress getAddress() {
return address;
}
/**
* @return the type of the proxy.
*/
public Type getType() {
return type;
}
/**
* @return the proxy user name.
*/
public String getUsername() {
return this.username;
}
/**
* @return the proxy password.
*/
public String getPassword() {
return this.password;
}
/**
* @return the hosts that bypass the proxy.
*/
public String getNonProxyHosts() {
return this.nonProxyHosts;
}
/**
* Attempts to load a proxy from the environment.
* <p>
* If a proxy is found and loaded the proxy address is DNS resolved.
* <p>
* Environment configurations are loaded in this order:
* <ol>
* <li>Azure HTTPS</li>
* <li>Azure HTTP</li>
* <li>Java HTTPS</li>
* <li>Java HTTP</li>
* </ol>
*
* Azure proxy configurations will be preferred over Java proxy configurations as they are more closely scoped to
* the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred.
*
* <p>
* {@code null} will be returned if no proxy was found in the environment.
*
* @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If
* {@code null} is passed then {@link Configuration
* Configuration
* @return A {@link ProxyOptions} reflecting a proxy loaded from the environment, if no proxy is found {@code null}
* will be returned.
* @throws IllegalArgumentException If {@code configuration} is {@link Configuration
*/
/**
* Attempts to load a proxy from the environment.
* <p>
* If a proxy is found and loaded, the proxy address is DNS resolved based on {@code createUnresolved}. When {@code
* createUnresolved} is true resolving {@link
* calls.
* <p>
* Environment configurations are loaded in this order:
* <ol>
* <li>Azure HTTPS</li>
* <li>Azure HTTP</li>
* <li>Java HTTPS</li>
* <li>Java HTTP</li>
* </ol>
*
* Azure proxy configurations will be preferred over Java proxy configurations as they are more closely scoped to
* the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred.
* <p>
* {@code null} will be returned if no proxy was found in the environment.
*
* @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If
* {@code null} is passed then {@link Configuration
* Configuration
* @param createUnresolved Flag determining whether the returned {@link ProxyOptions} is unresolved.
* @return A {@link ProxyOptions} reflecting a proxy loaded from the environment, if no proxy is found {@code null}
* will be returned.
* @throws IllegalArgumentException If {@code configuration} is {@link Configuration
*/
public static ProxyOptions fromConfiguration(Configuration configuration, boolean createUnresolved) {
if (configuration == Configuration.NONE) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException(INVALID_CONFIGURATION_MESSAGE));
}
Configuration proxyConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
return attemptToLoadProxy(proxyConfiguration, createUnresolved);
}
private static ProxyOptions attemptToLoadProxy(Configuration configuration, boolean createUnresolved) {
ProxyOptions proxyOptions;
if (Boolean.parseBoolean(configuration.get(JAVA_SYSTEM_PROXY_PREREQUISITE))) {
proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTPS_PROXY);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from HTTPS_PROXY environment variable.");
return proxyOptions;
}
proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTP_PROXY);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from HTTP_PROXY environment variable.");
return proxyOptions;
}
}
proxyOptions = attemptToLoadJavaProxy(configuration, createUnresolved,
Properties.HTTPS_PROXY_HOST, Properties.HTTPS_PROXY_PORT, Properties.HTTPS_PROXY_USER, Properties.HTTPS_PROXY_PASSWORD, DEFAULT_HTTPS_PORT);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from JVM HTTPS system properties.");
return proxyOptions;
}
proxyOptions = attemptToLoadJavaProxy(configuration, createUnresolved,
Properties.HTTP_PROXY_HOST, Properties.HTTP_PROXY_PORT, Properties.HTTP_PROXY_USER, Properties.HTTP_PROXY_PASSWORD, DEFAULT_HTTP_PORT);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from JVM HTTP system properties.");
return proxyOptions;
}
return null;
}
private static ProxyOptions attemptToLoadSystemProxy(Configuration configuration, boolean createUnresolved,
String proxyProperty) {
String proxyConfiguration = configuration.get(proxyProperty);
if (CoreUtils.isNullOrEmpty(proxyConfiguration)) {
return null;
}
try {
URL proxyUrl = new URL(proxyConfiguration);
int port = (proxyUrl.getPort() == -1) ? proxyUrl.getDefaultPort() : proxyUrl.getPort();
InetSocketAddress socketAddress = (createUnresolved)
? InetSocketAddress.createUnresolved(proxyUrl.getHost(), port)
: new InetSocketAddress(proxyUrl.getHost(), port);
ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, socketAddress);
String nonProxyHostsString = configuration.get(Configuration.PROPERTY_NO_PROXY);
if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) {
proxyOptions.nonProxyHosts = sanitizeNoProxy(nonProxyHostsString);
LOGGER.log(LogLevel.VERBOSE, () -> "Using non-proxy host regex: " + proxyOptions.nonProxyHosts);
}
String userInfo = proxyUrl.getUserInfo();
if (userInfo != null) {
String[] usernamePassword = userInfo.split(":", 2);
if (usernamePassword.length == 2) {
try {
proxyOptions.setCredentials(
URLDecoder.decode(usernamePassword[0], StandardCharsets.UTF_8.toString()),
URLDecoder.decode(usernamePassword[1], StandardCharsets.UTF_8.toString())
);
} catch (UnsupportedEncodingException e) {
return null;
}
}
}
return proxyOptions;
} catch (MalformedURLException ex) {
LOGGER.warning(INVALID_AZURE_PROXY_URL, proxyProperty);
return null;
}
}
/*
* Helper function that sanitizes 'NO_PROXY' into a Pattern safe string.
*/
static String sanitizeNoProxy(String noProxyString) {
return sanitizeNonProxyHosts(NO_PROXY_SPLIT.split(noProxyString));
}
private static ProxyOptions attemptToLoadJavaProxy(Configuration configuration, boolean createUnresolved,
ConfigurationProperty<String> hostProperty,
ConfigurationProperty<Integer> portProperty,
ConfigurationProperty<String> userProperty,
ConfigurationProperty<String> passwordProperty,
Integer defaultPort) {
String host = configuration.get(hostProperty);
if (CoreUtils.isNullOrEmpty(host)) {
return null;
}
int port;
try {
port = configuration.get(portProperty);
} catch (NumberFormatException ex) {
port = defaultPort;
}
InetSocketAddress socketAddress = (createUnresolved)
? InetSocketAddress.createUnresolved(host, port)
: new InetSocketAddress(host, port);
ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, socketAddress);
String nonProxyHostsString = configuration.get(Properties.NO_PROXY);
if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) {
proxyOptions.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHostsString);
LOGGER.log(LogLevel.VERBOSE, () -> "Using non-proxy host regex: " + proxyOptions.nonProxyHosts);
}
String username = configuration.get(userProperty);
String password = configuration.get(passwordProperty);
if (username != null && password != null) {
proxyOptions.setCredentials(username, password);
}
return proxyOptions;
}
/*
* Helper function that sanitizes 'http.nonProxyHosts' into a Pattern safe string.
*/
static String sanitizeJavaHttpNonProxyHosts(String nonProxyHostsString) {
return sanitizeNonProxyHosts(HTTP_NON_PROXY_HOSTS_SPLIT.split(nonProxyHostsString));
}
private static String sanitizeNonProxyHosts(String[] nonProxyHosts) {
StringBuilder sanitizedBuilder = new StringBuilder();
for (int i = 0; i < nonProxyHosts.length; i++) {
if (i > 0) {
sanitizedBuilder.append("|");
}
String prefixWildcard = "";
String suffixWildcard = "";
String sanitizedNonProxyHost = nonProxyHosts[i];
/*
* If the non-proxy host begins with either '.', '*', '.*', or any of the previous with a trailing '?'
* substring the non-proxy host and set the wildcard prefix.
*/
if (sanitizedNonProxyHost.startsWith(".")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1);
} else if (sanitizedNonProxyHost.startsWith(".?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
} else if (sanitizedNonProxyHost.startsWith("*?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
} else if (sanitizedNonProxyHost.startsWith("*")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1);
} else if (sanitizedNonProxyHost.startsWith(".*?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(3);
} else if (sanitizedNonProxyHost.startsWith(".*")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
}
/*
* Same with the ending of the non-proxy host, if it has a suffix wildcard trim the non-proxy host and
* retain the suffix wildcard.
*/
if (sanitizedNonProxyHost.endsWith(".")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2);
} else if (sanitizedNonProxyHost.endsWith(".?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
} else if (sanitizedNonProxyHost.endsWith("*?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
} else if (sanitizedNonProxyHost.endsWith("*")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2);
} else if (sanitizedNonProxyHost.endsWith(".*?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 4);
} else if (sanitizedNonProxyHost.endsWith(".*")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
}
try {
String attemptToSanitizeAsRegex = sanitizedNonProxyHost;
attemptToSanitizeAsRegex = UNESCAPED_PERIOD.matcher(attemptToSanitizeAsRegex).replaceAll("\\\\.");
attemptToSanitizeAsRegex = ANY.matcher(attemptToSanitizeAsRegex).replaceAll("\\.*?");
sanitizedNonProxyHost = Pattern.compile(attemptToSanitizeAsRegex).pattern();
} catch (PatternSyntaxException ex) {
/*
* Replace the non-proxy host with the sanitized value.
*
* The body of the non-proxy host is quoted to handle scenarios such a '127.0.0.1' or '*.azure.com'
* where without quoting the '.' in the string would be treated as the match any character instead of
* the literal '.' character.
*/
sanitizedNonProxyHost = Pattern.quote(sanitizedNonProxyHost);
}
sanitizedBuilder.append("(")
.append(prefixWildcard)
.append(sanitizedNonProxyHost)
.append(suffixWildcard)
.append(")");
}
return sanitizedBuilder.toString();
}
/**
* The type of the proxy.
*/
public enum Type {
/**
* HTTP proxy type.
*/
HTTP(Proxy.Type.HTTP),
/**
* SOCKS4 proxy type.
*/
SOCKS4(Proxy.Type.SOCKS),
/**
* SOCKS5 proxy type.
*/
SOCKS5(Proxy.Type.SOCKS);
private final Proxy.Type proxyType;
Type(Proxy.Type proxyType) {
this.proxyType = proxyType;
}
/**
* Get the {@link Proxy.Type} equivalent of this type.
*
* @return the proxy type
*/
public Proxy.Type toProxyType() {
return proxyType;
}
}
private static class Properties {
public static final ConfigurationProperty<String> NO_PROXY = ConfigurationProperty.stringPropertyBuilder("http.proxy.non-proxy-hosts")
.environmentAliases("http.nonProxyHosts", Configuration.PROPERTY_NO_PROXY)
.canLogValue(true)
.build();
public static final ConfigurationProperty<Boolean> CREATE_UNRESOLVED = ConfigurationUtils.booleanSharedPropertyBuilder("http.proxy.create-unresolved")
.defaultValue(false)
.build();
public static final ConfigurationProperty<String> HTTP_PROXY_HOST = ConfigurationUtils.stringSharedPropertyBuilder("http.proxy.host")
.environmentAliases("http.proxyHost")
.canLogValue(true)
.build();
public static final ConfigurationProperty<Integer> HTTP_PROXY_PORT = ConfigurationUtils.integerSharedPropertyBuilder("http.proxy.port")
.environmentAliases("http.proxyPort")
.defaultValue(DEFAULT_HTTP_PORT)
.build();
public static final ConfigurationProperty<String> HTTP_PROXY_USER = ConfigurationUtils.stringSharedPropertyBuilder("http.proxy.username")
.environmentAliases("http.proxyUser")
.build();
public static final ConfigurationProperty<String> HTTP_PROXY_PASSWORD = ConfigurationUtils.stringSharedPropertyBuilder("http.proxy.password")
.environmentAliases("http.proxyPassword")
.build();
public static final ConfigurationProperty<String> HTTPS_PROXY_HOST = ConfigurationUtils.stringSharedPropertyBuilder("https.proxy.host")
.environmentAliases("https.proxyHost")
.canLogValue(true)
.build();
public static final ConfigurationProperty<Integer> HTTPS_PROXY_PORT = ConfigurationUtils.integerSharedPropertyBuilder("https.proxy.port")
.environmentAliases("https.proxyPort")
.defaultValue(DEFAULT_HTTPS_PORT)
.build();
public static final ConfigurationProperty<String> HTTPS_PROXY_USER = ConfigurationUtils.stringSharedPropertyBuilder("https.proxy.username")
.environmentAliases("https.proxyUser")
.build();
public static final ConfigurationProperty<String> HTTPS_PROXY_PASSWORD = ConfigurationUtils.stringSharedPropertyBuilder("https.proxy.password")
.environmentAliases("https.proxyPassword")
.build();
}
} | class ProxyOptions {
private static final ClientLogger LOGGER = new ClientLogger(ProxyOptions.class);
private static final String INVALID_AZURE_PROXY_URL = "Configuration {} is an invalid URL and is being ignored.";
/*
* This indicates whether system proxy configurations (HTTPS_PROXY, HTTP_PROXY) are allowed to be used.
*/
private static final String JAVA_SYSTEM_PROXY_PREREQUISITE = "java.net.useSystemProxies";
/*
* Java environment variables related to proxies. The protocol is removed since these are the same for 'https' and
* 'http', the exception is 'http.nonProxyHosts' as it is used for both.
*/
private static final String JAVA_PROXY_HOST = "proxyHost";
private static final String JAVA_PROXY_PORT = "proxyPort";
private static final String JAVA_PROXY_USER = "proxyUser";
private static final String JAVA_PROXY_PASSWORD = "proxyPassword";
private static final String JAVA_NON_PROXY_HOSTS = "http.nonProxyHosts";
private static final String HTTPS = "https";
private static final int DEFAULT_HTTPS_PORT = 443;
private static final String HTTP = "http";
private static final int DEFAULT_HTTP_PORT = 80;
/*
* The 'http.nonProxyHosts' system property is expected to be delimited by '|', but don't split escaped '|'s.
*/
private static final Pattern HTTP_NON_PROXY_HOSTS_SPLIT = Pattern.compile("(?<!\\\\)\\|");
/*
* The 'NO_PROXY' environment variable is expected to be delimited by ',', but don't split escaped ','s.
*/
private static final Pattern NO_PROXY_SPLIT = Pattern.compile("(?<!\\\\),");
private static final Pattern UNESCAPED_PERIOD = Pattern.compile("(?<!\\\\)\\.");
private static final Pattern ANY = Pattern.compile("\\*");
private static final ConfigurationProperty<String> NON_PROXY_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_NON_PROXY_HOSTS)
.shared(true)
.logValue(true)
.build();
private static final ConfigurationProperty<String> HOST_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_HOST)
.shared(true)
.logValue(true)
.build();
private static final ConfigurationProperty<Integer> PORT_PROPERTY = ConfigurationPropertyBuilder.ofInteger(ConfigurationProperties.HTTP_PROXY_PORT)
.shared(true)
.defaultValue(DEFAULT_HTTPS_PORT)
.build();
private static final ConfigurationProperty<String> USER_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_USER)
.shared(true)
.logValue(true)
.build();
private static final ConfigurationProperty<String> PASSWORD_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_PASSWORD)
.shared(true)
.build();
private final InetSocketAddress address;
private final Type type;
private String username;
private String password;
private String nonProxyHosts;
/**
* Creates ProxyOptions.
*
* @param type the proxy type
* @param address the proxy address (ip and port number)
*/
public ProxyOptions(Type type, InetSocketAddress address) {
this.type = type;
this.address = address;
}
/**
* Set the proxy credentials.
*
* @param username proxy user name
* @param password proxy password
* @return the updated ProxyOptions object
*/
public ProxyOptions setCredentials(String username, String password) {
this.username = Objects.requireNonNull(username, "'username' cannot be null.");
this.password = Objects.requireNonNull(password, "'password' cannot be null.");
return this;
}
/**
* Sets the hosts which bypass the proxy.
* <p>
* The expected format of the passed string is a {@code '|'} delimited list of hosts which should bypass the proxy.
* Individual host strings may contain regex characters such as {@code '*'}.
*
* @param nonProxyHosts Hosts that bypass the proxy.
* @return the updated ProxyOptions object
*/
public ProxyOptions setNonProxyHosts(String nonProxyHosts) {
this.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHosts);
return this;
}
/**
* @return the address of the proxy.
*/
public InetSocketAddress getAddress() {
return address;
}
/**
* @return the type of the proxy.
*/
public Type getType() {
return type;
}
/**
* @return the proxy user name.
*/
public String getUsername() {
return this.username;
}
/**
* @return the proxy password.
*/
public String getPassword() {
return this.password;
}
/**
* @return the hosts that bypass the proxy.
*/
public String getNonProxyHosts() {
return this.nonProxyHosts;
}
/**
* Attempts to load a proxy from the configuration.
* <p>
* If a proxy is found and loaded the proxy address is DNS resolved.
* <p>
* Environment configurations are loaded in this order:
* <ol>
* <li>Azure HTTPS</li>
* <li>Azure HTTP</li>
* <li>Java HTTPS</li>
* <li>Java HTTP</li>
* </ol>
*
* Azure proxy configurations will be preferred over Java proxy configurations as they are more closely scoped to
* the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred.
*
* <p>
* {@code null} will be returned if no proxy was found in the environment.
*
* @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If
* {@code null} is passed then {@link Configuration
* @return A {@link ProxyOptions} reflecting a proxy loaded from the environment, if no proxy is found {@code null}
* will be returned.
*/
/**
* Attempts to load a proxy from the environment.
* <p>
* If a proxy is found and loaded, the proxy address is DNS resolved based on {@code createUnresolved}. When {@code
* createUnresolved} is true resolving {@link
* calls.
* <p>
* Environment configurations are loaded in this order:
* <ol>
* <li>Azure HTTPS</li>
* <li>Azure HTTP</li>
* <li>Java HTTPS</li>
* <li>Java HTTP</li>
* </ol>
*
* Azure proxy configurations will be preferred over Java proxy configurations as they are more closely scoped to
* the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred.
* <p>
* {@code null} will be returned if no proxy was found in the environment.
*
* @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If
* {@code null} is passed then {@link Configuration
* Configuration
* @param createUnresolved Flag determining whether the returned {@link ProxyOptions} is unresolved.
* @return A {@link ProxyOptions} reflecting a proxy loaded from the environment, if no proxy is found {@code null}
* will be returned.
*/
public static ProxyOptions fromConfiguration(Configuration configuration, boolean createUnresolved) {
Configuration proxyConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
return attemptToLoadProxy(proxyConfiguration, createUnresolved);
}
private static ProxyOptions attemptToLoadProxy(Configuration configuration, boolean createUnresolved) {
if (configuration == Configuration.NONE) {
return null;
}
ProxyOptions proxyOptions = null;
if (Boolean.parseBoolean(configuration.get(JAVA_SYSTEM_PROXY_PREREQUISITE))) {
proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTPS_PROXY);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from HTTPS_PROXY environment variable.");
return proxyOptions;
}
proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTP_PROXY);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from HTTP_PROXY environment variable.");
return proxyOptions;
}
}
proxyOptions = attemptToLoadAzureSdkProxy(configuration, createUnresolved);
if (proxyOptions != null) {
return proxyOptions;
}
proxyOptions = attemptToLoadJavaProxy(configuration, createUnresolved, HTTPS);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from JVM HTTPS system properties.");
return proxyOptions;
}
proxyOptions = attemptToLoadJavaProxy(configuration, createUnresolved, HTTP);
if (proxyOptions != null) {
LOGGER.verbose("Using proxy created from JVM HTTP system properties.");
return proxyOptions;
}
return null;
}
private static ProxyOptions attemptToLoadSystemProxy(Configuration configuration, boolean createUnresolved,
String proxyProperty) {
String proxyConfiguration = configuration.get(proxyProperty);
if (CoreUtils.isNullOrEmpty(proxyConfiguration)) {
return null;
}
try {
URL proxyUrl = new URL(proxyConfiguration);
int port = (proxyUrl.getPort() == -1) ? proxyUrl.getDefaultPort() : proxyUrl.getPort();
InetSocketAddress socketAddress = (createUnresolved)
? InetSocketAddress.createUnresolved(proxyUrl.getHost(), port)
: new InetSocketAddress(proxyUrl.getHost(), port);
ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, socketAddress);
String nonProxyHostsString = configuration.get(Configuration.PROPERTY_NO_PROXY);
if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) {
proxyOptions.nonProxyHosts = sanitizeNoProxy(nonProxyHostsString);
LOGGER.log(LogLevel.VERBOSE, () -> "Using non-proxy host regex: " + proxyOptions.nonProxyHosts);
}
String userInfo = proxyUrl.getUserInfo();
if (userInfo != null) {
String[] usernamePassword = userInfo.split(":", 2);
if (usernamePassword.length == 2) {
try {
proxyOptions.setCredentials(
URLDecoder.decode(usernamePassword[0], StandardCharsets.UTF_8.toString()),
URLDecoder.decode(usernamePassword[1], StandardCharsets.UTF_8.toString())
);
} catch (UnsupportedEncodingException e) {
return null;
}
}
}
return proxyOptions;
} catch (MalformedURLException ex) {
LOGGER.warning(INVALID_AZURE_PROXY_URL, proxyProperty);
return null;
}
}
/*
* Helper function that sanitizes 'NO_PROXY' into a Pattern safe string.
*/
static String sanitizeNoProxy(String noProxyString) {
return sanitizeNonProxyHosts(NO_PROXY_SPLIT.split(noProxyString));
}
private static ProxyOptions attemptToLoadJavaProxy(Configuration configuration, boolean createUnresolved,
String type) {
String host = configuration.get(type + "." + JAVA_PROXY_HOST);
if (CoreUtils.isNullOrEmpty(host)) {
return null;
}
int port;
try {
port = Integer.parseInt(configuration.get(type + "." + JAVA_PROXY_PORT));
} catch (NumberFormatException ex) {
port = HTTPS.equals(type) ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT;
}
String nonProxyHostsString = configuration.get(JAVA_NON_PROXY_HOSTS);
String username = configuration.get(type + "." + JAVA_PROXY_USER);
String password = configuration.get(type + "." + JAVA_PROXY_PASSWORD);
return createOptions(host, port, nonProxyHostsString, username, password, createUnresolved);
}
private static ProxyOptions attemptToLoadAzureSdkProxy(Configuration configuration, boolean createUnresolved) {
String host = configuration.get(HOST_PROPERTY);
if (CoreUtils.isNullOrEmpty(host)) {
return null;
}
int port = configuration.get(PORT_PROPERTY);
String nonProxyHostsString = configuration.get(NON_PROXY_PROPERTY);
String username = configuration.get(USER_PROPERTY);
String password = configuration.get(PASSWORD_PROPERTY);
return createOptions(host, port, nonProxyHostsString, username, password, createUnresolved);
}
private static ProxyOptions createOptions(String host, int port, String nonProxyHostsString, String username, String password, boolean createUnresolved) {
InetSocketAddress socketAddress = (createUnresolved)
? InetSocketAddress.createUnresolved(host, port)
: new InetSocketAddress(host, port);
ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, socketAddress);
if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) {
proxyOptions.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHostsString);
LOGGER.log(LogLevel.VERBOSE, () -> "Using non-proxy host regex: " + proxyOptions.nonProxyHosts);
}
if (username != null && password != null) {
proxyOptions.setCredentials(username, password);
}
return proxyOptions;
}
/*
* Helper function that sanitizes 'http.nonProxyHosts' into a Pattern safe string.
*/
static String sanitizeJavaHttpNonProxyHosts(String nonProxyHostsString) {
return sanitizeNonProxyHosts(HTTP_NON_PROXY_HOSTS_SPLIT.split(nonProxyHostsString));
}
private static String sanitizeNonProxyHosts(String[] nonProxyHosts) {
StringBuilder sanitizedBuilder = new StringBuilder();
for (int i = 0; i < nonProxyHosts.length; i++) {
if (i > 0) {
sanitizedBuilder.append("|");
}
String prefixWildcard = "";
String suffixWildcard = "";
String sanitizedNonProxyHost = nonProxyHosts[i];
/*
* If the non-proxy host begins with either '.', '*', '.*', or any of the previous with a trailing '?'
* substring the non-proxy host and set the wildcard prefix.
*/
if (sanitizedNonProxyHost.startsWith(".")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1);
} else if (sanitizedNonProxyHost.startsWith(".?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
} else if (sanitizedNonProxyHost.startsWith("*?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
} else if (sanitizedNonProxyHost.startsWith("*")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1);
} else if (sanitizedNonProxyHost.startsWith(".*?")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(3);
} else if (sanitizedNonProxyHost.startsWith(".*")) {
prefixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2);
}
/*
* Same with the ending of the non-proxy host, if it has a suffix wildcard trim the non-proxy host and
* retain the suffix wildcard.
*/
if (sanitizedNonProxyHost.endsWith(".")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2);
} else if (sanitizedNonProxyHost.endsWith(".?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
} else if (sanitizedNonProxyHost.endsWith("*?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
} else if (sanitizedNonProxyHost.endsWith("*")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2);
} else if (sanitizedNonProxyHost.endsWith(".*?")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 4);
} else if (sanitizedNonProxyHost.endsWith(".*")) {
suffixWildcard = ".*?";
sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3);
}
try {
String attemptToSanitizeAsRegex = sanitizedNonProxyHost;
attemptToSanitizeAsRegex = UNESCAPED_PERIOD.matcher(attemptToSanitizeAsRegex).replaceAll("\\\\.");
attemptToSanitizeAsRegex = ANY.matcher(attemptToSanitizeAsRegex).replaceAll("\\.*?");
sanitizedNonProxyHost = Pattern.compile(attemptToSanitizeAsRegex).pattern();
} catch (PatternSyntaxException ex) {
/*
* Replace the non-proxy host with the sanitized value.
*
* The body of the non-proxy host is quoted to handle scenarios such a '127.0.0.1' or '*.azure.com'
* where without quoting the '.' in the string would be treated as the match any character instead of
* the literal '.' character.
*/
sanitizedNonProxyHost = Pattern.quote(sanitizedNonProxyHost);
}
sanitizedBuilder.append("(")
.append(prefixWildcard)
.append(sanitizedNonProxyHost)
.append(suffixWildcard)
.append(")");
}
return sanitizedBuilder.toString();
}
/**
* The type of the proxy.
*/
public enum Type {
/**
* HTTP proxy type.
*/
HTTP(Proxy.Type.HTTP),
/**
* SOCKS4 proxy type.
*/
SOCKS4(Proxy.Type.SOCKS),
/**
* SOCKS5 proxy type.
*/
SOCKS5(Proxy.Type.SOCKS);
private final Proxy.Type proxyType;
Type(Proxy.Type proxyType) {
this.proxyType = proxyType;
}
/**
* Get the {@link Proxy.Type} equivalent of this type.
*
* @return the proxy type
*/
public Proxy.Type toProxyType() {
return proxyType;
}
}
/**
* Lists available configuration property names for HTTP {@link ProxyOptions}.
*/
private static class ConfigurationProperties {
/**
* Represents a list of hosts that should be reached directly, bypassing the proxy.
* This is a list of patterns separated by '|'. The patterns may start or end with a '*' for wildcards.
* Any host matching one of these patterns will be reached through a direct connection instead of through a proxy.
* <p>
* Default value is {@code null}
*/
public static final String HTTP_PROXY_NON_PROXY_HOSTS = "http.proxy.non-proxy-hosts";
/**
* The HTTP host name of the proxy server.
* <p>
* Default value is {@code null}.
*/
public static final String HTTP_PROXY_HOST = "http.proxy.hostname";
/**
* The port number of the proxy server.
* <p>
* Default value is {@code 443}.
*/
public static final String HTTP_PROXY_PORT = "http.proxy.port";
/**
* The HTTP proxy server user.
* Default value is {@code null}.
*/
public static final String HTTP_PROXY_USER = "http.proxy.username";
/**
* The HTTP proxy server password.
* Default value is {@code null}.
*/
public static final String HTTP_PROXY_PASSWORD = "http.proxy.password";
}
} |
`StandardCharsets.UTF_8.name()` is more durable than a String constant | private static String decode(final String stringToDecode) {
try {
return URLDecoder.decode(stringToDecode, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
} | return URLDecoder.decode(stringToDecode, StandardCharsets.UTF_8.name()); | private static String decode(final String stringToDecode) {
try {
return URLDecoder.decode(stringToDecode, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
} | class Utility {
private static final ClientLogger LOGGER = new ClientLogger(Utility.class);
/**
* Please see <a href=https:
* for more information on Azure resource provider namespaces.
*/
public static final String STORAGE_TRACING_NAMESPACE_VALUE = "Microsoft.Storage";
/**
* Performs a safe decoding of the passed string, taking care to preserve each {@code +} character rather than
* replacing it with a space character.
*
* @param stringToDecode String value to decode
* @return the decoded string value
* @throws RuntimeException If the UTF-8 charset isn't supported
*/
public static String urlDecode(final String stringToDecode) {
if (CoreUtils.isNullOrEmpty(stringToDecode)) {
return "";
}
if (stringToDecode.contains("+")) {
StringBuilder outBuilder = new StringBuilder();
int startDex = 0;
for (int m = 0; m < stringToDecode.length(); m++) {
if (stringToDecode.charAt(m) == '+') {
if (m > startDex) {
outBuilder.append(decode(stringToDecode.substring(startDex, m)));
}
outBuilder.append("+");
startDex = m + 1;
}
}
if (startDex != stringToDecode.length()) {
outBuilder.append(decode(stringToDecode.substring(startDex)));
}
return outBuilder.toString();
} else {
return decode(stringToDecode);
}
}
/*
* Helper method to reduce duplicate calls of URLDecoder.decode
*/
/**
* Performs a safe encoding of the specified string, taking care to insert %20 for each space character instead of
* inserting the {@code +} character.
*
* @param stringToEncode String value to encode
* @return the encoded string value
* @throws RuntimeException If the UTF-8 charset ins't supported
*/
public static String urlEncode(final String stringToEncode) {
if (stringToEncode == null) {
return null;
}
if (stringToEncode.length() == 0) {
return "";
}
if (stringToEncode.contains(" ")) {
StringBuilder outBuilder = new StringBuilder();
int startDex = 0;
for (int m = 0; m < stringToEncode.length(); m++) {
if (stringToEncode.charAt(m) == ' ') {
if (m > startDex) {
outBuilder.append(encode(stringToEncode.substring(startDex, m)));
}
outBuilder.append("%20");
startDex = m + 1;
}
}
if (startDex != stringToEncode.length()) {
outBuilder.append(encode(stringToEncode.substring(startDex)));
}
return outBuilder.toString();
} else {
return encode(stringToEncode);
}
}
/*
* Helper method to reduce duplicate calls of URLEncoder.encode
*/
private static String encode(final String stringToEncode) {
try {
return URLEncoder.encode(stringToEncode, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
}
/**
* Performs a safe encoding of a url string, only encoding the path.
*
* @param url The url to encode.
* @return The encoded url.
*/
public static String encodeUrlPath(String url) {
/* Deconstruct the URL and reconstruct it making sure the path is encoded. */
UrlBuilder builder = UrlBuilder.parse(url);
String path = builder.getPath();
if (path.startsWith("/")) {
path = path.substring(1);
}
path = Utility.urlEncode(Utility.urlDecode(path));
builder.setPath(path);
return builder.toString();
}
/**
* Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it with up to
* millisecond precision.
*
* @param dateString the {@code String} to be interpreted as a <code>Date</code>
* @return the corresponding <code>Date</code> object
* @throws IllegalArgumentException If {@code dateString} doesn't match an ISO8601 pattern
* @deprecated Use {@link StorageImplUtils
*/
@Deprecated
public static OffsetDateTime parseDate(String dateString) {
return StorageImplUtils.parseDateAndFormat(dateString).getDateTime();
}
/**
* A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length
* and the input length.
*
* @param data The input data which needs to convert to ByteBuffer.
* @param length The expected input data length.
* @param blockSize The size of each ByteBuffer.
* @return {@link ByteBuffer} which contains the input data.
* @throws UnexpectedLengthException when input data length mismatch input length.
* @throws RuntimeException When I/O error occurs.
*/
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) {
return convertStreamToByteBuffer(data, length, blockSize, true);
}
/**
* A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length
* and the input length.
*
* Using markAndReset=true to force a seekable stream implies a buffering strategy is not being used, in which case
* length is still needed for whatever underlying REST call is being streamed to. If markAndReset=false and data is
* being buffered, consider using {@link com.azure.core.util.FluxUtil
* does not require a data length.
*
* @param data The input data which needs to convert to ByteBuffer.
* @param length The expected input data length.
* @param blockSize The size of each ByteBuffer.
* @param markAndReset Whether the stream needs to be marked and reset. This should generally always be true to
* support retries. It is false in the case of buffered upload to support non markable streams because buffered
* upload uses its own mechanisms to support retries.
* @return {@link ByteBuffer} which contains the input data.
* @throws UnexpectedLengthException when input data length mismatch input length.
* @throws RuntimeException When I/O error occurs.
*/
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize,
boolean markAndReset) {
if (markAndReset) {
data.mark(Integer.MAX_VALUE);
}
if (length == 0) {
try {
if (data.read() != -1) {
long totalLength = 1 + data.available();
throw LOGGER.logExceptionAsError(new UnexpectedLengthException(
String.format("Request body emitted %d bytes, more than the expected %d bytes.",
totalLength, length), totalLength, length));
}
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new RuntimeException("I/O errors occurred", e));
}
}
return Flux.defer(() -> {
/*
If the request needs to be retried, the flux will be resubscribed to. The stream and counter must be
reset in order to correctly return the same data again.
*/
final long[] currentTotalLength = new long[1];
if (markAndReset) {
try {
data.reset();
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new RuntimeException(e));
}
}
return Flux.range(0, (int) Math.ceil((double) length / (double) blockSize))
.map(i -> i * blockSize)
.concatMap(pos -> Mono.fromCallable(() -> {
long count = pos + blockSize > length ? length - pos : blockSize;
byte[] cache = new byte[(int) count];
int numOfBytes = 0;
int offset = 0;
int len = (int) count;
while (numOfBytes != -1 && offset < count) {
numOfBytes = data.read(cache, offset, len);
if (numOfBytes != -1) {
offset += numOfBytes;
len -= numOfBytes;
currentTotalLength[0] += numOfBytes;
}
}
if (numOfBytes == -1 && currentTotalLength[0] < length) {
throw LOGGER.logExceptionAsError(new UnexpectedLengthException(
String.format("Request body emitted %d bytes, less than the expected %d bytes.",
currentTotalLength[0], length), currentTotalLength[0], length));
}
if (currentTotalLength[0] >= length) {
try {
if (data.read() != -1) {
long totalLength = 1 + currentTotalLength[0] + data.available();
throw LOGGER.logExceptionAsError(new UnexpectedLengthException(
String.format("Request body emitted %d bytes, more than the expected %d bytes.",
totalLength, length), totalLength, length));
} else if (currentTotalLength[0] > length) {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("Read more data than was requested. Size of data read: %d. Size of data"
+ " requested: %d", currentTotalLength[0], length)));
}
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new RuntimeException("I/O errors occurred", e));
}
}
return ByteBuffer.wrap(cache, 0, offset);
}));
});
}
/**
* Appends a query parameter to a url.
*
* @param url The url.
* @param key The query key.
* @param value The query value.
* @return The updated url.
*/
public static String appendQueryParameter(String url, String key, String value) {
if (url.contains("?")) {
url = String.format("%s&%s=%s", url, key, value);
} else {
url = String.format("%s?%s=%s", url, key, value);
}
return url;
}
} | class Utility {
private static final ClientLogger LOGGER = new ClientLogger(Utility.class);
/**
* Please see <a href=https:
* for more information on Azure resource provider namespaces.
*/
public static final String STORAGE_TRACING_NAMESPACE_VALUE = "Microsoft.Storage";
/**
* Performs a safe decoding of the passed string, taking care to preserve each {@code +} character rather than
* replacing it with a space character.
*
* @param stringToDecode String value to decode
* @return the decoded string value
* @throws RuntimeException If the UTF-8 charset isn't supported
*/
public static String urlDecode(final String stringToDecode) {
if (CoreUtils.isNullOrEmpty(stringToDecode)) {
return "";
}
if (stringToDecode.contains("+")) {
StringBuilder outBuilder = new StringBuilder();
int startDex = 0;
for (int m = 0; m < stringToDecode.length(); m++) {
if (stringToDecode.charAt(m) == '+') {
if (m > startDex) {
outBuilder.append(decode(stringToDecode.substring(startDex, m)));
}
outBuilder.append("+");
startDex = m + 1;
}
}
if (startDex != stringToDecode.length()) {
outBuilder.append(decode(stringToDecode.substring(startDex)));
}
return outBuilder.toString();
} else {
return decode(stringToDecode);
}
}
/*
* Helper method to reduce duplicate calls of URLDecoder.decode
*/
/**
* Performs a safe encoding of the specified string, taking care to insert %20 for each space character instead of
* inserting the {@code +} character.
*
* @param stringToEncode String value to encode
* @return the encoded string value
* @throws RuntimeException If the UTF-8 charset ins't supported
*/
public static String urlEncode(final String stringToEncode) {
if (stringToEncode == null) {
return null;
}
if (stringToEncode.length() == 0) {
return "";
}
if (stringToEncode.contains(" ")) {
StringBuilder outBuilder = new StringBuilder();
int startDex = 0;
for (int m = 0; m < stringToEncode.length(); m++) {
if (stringToEncode.charAt(m) == ' ') {
if (m > startDex) {
outBuilder.append(encode(stringToEncode.substring(startDex, m)));
}
outBuilder.append("%20");
startDex = m + 1;
}
}
if (startDex != stringToEncode.length()) {
outBuilder.append(encode(stringToEncode.substring(startDex)));
}
return outBuilder.toString();
} else {
return encode(stringToEncode);
}
}
/*
* Helper method to reduce duplicate calls of URLEncoder.encode
*/
private static String encode(final String stringToEncode) {
try {
return URLEncoder.encode(stringToEncode, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
}
/**
* Performs a safe encoding of a url string, only encoding the path.
*
* @param url The url to encode.
* @return The encoded url.
*/
public static String encodeUrlPath(String url) {
/* Deconstruct the URL and reconstruct it making sure the path is encoded. */
UrlBuilder builder = UrlBuilder.parse(url);
String path = builder.getPath();
if (path.startsWith("/")) {
path = path.substring(1);
}
path = Utility.urlEncode(Utility.urlDecode(path));
builder.setPath(path);
return builder.toString();
}
/**
* Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it with up to
* millisecond precision.
*
* @param dateString the {@code String} to be interpreted as a <code>Date</code>
* @return the corresponding <code>Date</code> object
* @throws IllegalArgumentException If {@code dateString} doesn't match an ISO8601 pattern
* @deprecated Use {@link StorageImplUtils
*/
@Deprecated
public static OffsetDateTime parseDate(String dateString) {
return StorageImplUtils.parseDateAndFormat(dateString).getDateTime();
}
/**
* A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length
* and the input length.
*
* @param data The input data which needs to convert to ByteBuffer.
* @param length The expected input data length.
* @param blockSize The size of each ByteBuffer.
* @return {@link ByteBuffer} which contains the input data.
* @throws UnexpectedLengthException when input data length mismatch input length.
* @throws RuntimeException When I/O error occurs.
*/
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) {
return convertStreamToByteBuffer(data, length, blockSize, true);
}
/**
* A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length
* and the input length.
*
* Using markAndReset=true to force a seekable stream implies a buffering strategy is not being used, in which case
* length is still needed for whatever underlying REST call is being streamed to. If markAndReset=false and data is
* being buffered, consider using {@link com.azure.core.util.FluxUtil
* does not require a data length.
*
* @param data The input data which needs to convert to ByteBuffer.
* @param length The expected input data length.
* @param blockSize The size of each ByteBuffer.
* @param markAndReset Whether the stream needs to be marked and reset. This should generally always be true to
* support retries. It is false in the case of buffered upload to support non markable streams because buffered
* upload uses its own mechanisms to support retries.
* @return {@link ByteBuffer} which contains the input data.
* @throws UnexpectedLengthException when input data length mismatch input length.
* @throws RuntimeException When I/O error occurs.
*/
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize,
boolean markAndReset) {
if (markAndReset) {
data.mark(Integer.MAX_VALUE);
}
if (length == 0) {
try {
if (data.read() != -1) {
long totalLength = 1 + data.available();
throw LOGGER.logExceptionAsError(new UnexpectedLengthException(
String.format("Request body emitted %d bytes, more than the expected %d bytes.",
totalLength, length), totalLength, length));
}
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new RuntimeException("I/O errors occurred", e));
}
}
return Flux.defer(() -> {
/*
If the request needs to be retried, the flux will be resubscribed to. The stream and counter must be
reset in order to correctly return the same data again.
*/
final long[] currentTotalLength = new long[1];
if (markAndReset) {
try {
data.reset();
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new RuntimeException(e));
}
}
return Flux.range(0, (int) Math.ceil((double) length / (double) blockSize))
.map(i -> i * blockSize)
.concatMap(pos -> Mono.fromCallable(() -> {
long count = pos + blockSize > length ? length - pos : blockSize;
byte[] cache = new byte[(int) count];
int numOfBytes = 0;
int offset = 0;
int len = (int) count;
while (numOfBytes != -1 && offset < count) {
numOfBytes = data.read(cache, offset, len);
if (numOfBytes != -1) {
offset += numOfBytes;
len -= numOfBytes;
currentTotalLength[0] += numOfBytes;
}
}
if (numOfBytes == -1 && currentTotalLength[0] < length) {
throw LOGGER.logExceptionAsError(new UnexpectedLengthException(
String.format("Request body emitted %d bytes, less than the expected %d bytes.",
currentTotalLength[0], length), currentTotalLength[0], length));
}
if (currentTotalLength[0] >= length) {
try {
if (data.read() != -1) {
long totalLength = 1 + currentTotalLength[0] + data.available();
throw LOGGER.logExceptionAsError(new UnexpectedLengthException(
String.format("Request body emitted %d bytes, more than the expected %d bytes.",
totalLength, length), totalLength, length));
} else if (currentTotalLength[0] > length) {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("Read more data than was requested. Size of data read: %d. Size of data"
+ " requested: %d", currentTotalLength[0], length)));
}
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new RuntimeException("I/O errors occurred", e));
}
}
return ByteBuffer.wrap(cache, 0, offset);
}));
});
}
/**
* Appends a query parameter to a url.
*
* @param url The url.
* @param key The query key.
* @param value The query value.
* @return The updated url.
*/
public static String appendQueryParameter(String url, String key, String value) {
if (url.contains("?")) {
url = String.format("%s&%s=%s", url, key, value);
} else {
url = String.format("%s?%s=%s", url, key, value);
}
return url;
}
} |
Need we test the case of disable auto comoplete here? | void customizeAutoComplete() {
consumerProperties.setAutoComplete(true);
assertTrue(consumerProperties.getAutoComplete());
} | consumerProperties.setAutoComplete(true); | void customizeAutoComplete() {
consumerProperties.setAutoComplete(false);
assertFalse(consumerProperties.getAutoComplete());
} | class ServiceBusConsumerPropertiesTests {
private ServiceBusConsumerProperties consumerProperties;
@BeforeEach
void beforeEach() {
consumerProperties = new ServiceBusConsumerProperties();
}
@Test
void autoCompleteDefaultTrue() {
assertTrue(consumerProperties.getAutoComplete());
}
@Test
@Test
void requeueRejectedDefaultsToFalse() {
assertFalse(consumerProperties.isRequeueRejected());
}
@Test
void customRequeueRejected() {
consumerProperties.setRequeueRejected(true);
assertTrue(consumerProperties.isRequeueRejected());
}
@Test
void maxConcurrentCallsDefaults() {
assertEquals(1, consumerProperties.getMaxConcurrentCalls());
}
@Test
void customMaxConcurrentCalls() {
consumerProperties.setMaxConcurrentCalls(10);
assertEquals(10, consumerProperties.getMaxConcurrentCalls());
}
@Test
void maxConcurrentSessionsDefaults() {
assertNull(consumerProperties.getMaxConcurrentSessions());
}
@Test
void customMaxConcurrentSessions() {
consumerProperties.setMaxConcurrentSessions(10);
assertEquals(10, consumerProperties.getMaxConcurrentSessions());
}
@Test
void subQueueDefaults() {
assertNotNull(consumerProperties.getSubQueue());
}
@Test
void customSubQueue() {
consumerProperties.setSubQueue(SubQueue.DEAD_LETTER_QUEUE);
assertEquals(SubQueue.DEAD_LETTER_QUEUE, consumerProperties.getSubQueue());
}
@Test
void receiveModeDefaults() {
assertEquals(ServiceBusReceiveMode.PEEK_LOCK, consumerProperties.getReceiveMode());
}
@Test
void customReceiveMode() {
consumerProperties.setReceiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE);
assertEquals(ServiceBusReceiveMode.RECEIVE_AND_DELETE, consumerProperties.getReceiveMode());
}
@Test
void maxAutoLockRenewDurationDefaults() {
assertEquals(Duration.ofMinutes(5), consumerProperties.getMaxAutoLockRenewDuration());
}
@Test
void customMaxAutoLockRenewDuration() {
Duration duration = Duration.ofMinutes(6);
consumerProperties.setMaxAutoLockRenewDuration(duration);
assertEquals(duration, consumerProperties.getMaxAutoLockRenewDuration());
}
} | class ServiceBusConsumerPropertiesTests {
private ServiceBusConsumerProperties consumerProperties;
@BeforeEach
void beforeEach() {
consumerProperties = new ServiceBusConsumerProperties();
}
@Test
void autoCompleteDefaultTrue() {
assertTrue(consumerProperties.getAutoComplete());
}
@Test
@Test
void requeueRejectedDefaultsToFalse() {
assertFalse(consumerProperties.isRequeueRejected());
}
@Test
void customRequeueRejected() {
consumerProperties.setRequeueRejected(true);
assertTrue(consumerProperties.isRequeueRejected());
}
@Test
void maxConcurrentCallsDefaults() {
assertEquals(1, consumerProperties.getMaxConcurrentCalls());
}
@Test
void customMaxConcurrentCalls() {
consumerProperties.setMaxConcurrentCalls(10);
assertEquals(10, consumerProperties.getMaxConcurrentCalls());
}
@Test
void maxConcurrentSessionsDefaults() {
assertNull(consumerProperties.getMaxConcurrentSessions());
}
@Test
void customMaxConcurrentSessions() {
consumerProperties.setMaxConcurrentSessions(10);
assertEquals(10, consumerProperties.getMaxConcurrentSessions());
}
@Test
void subQueueDefaults() {
assertNotNull(consumerProperties.getSubQueue());
}
@Test
void customSubQueue() {
consumerProperties.setSubQueue(SubQueue.DEAD_LETTER_QUEUE);
assertEquals(SubQueue.DEAD_LETTER_QUEUE, consumerProperties.getSubQueue());
}
@Test
void receiveModeDefaults() {
assertEquals(ServiceBusReceiveMode.PEEK_LOCK, consumerProperties.getReceiveMode());
}
@Test
void customReceiveMode() {
consumerProperties.setReceiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE);
assertEquals(ServiceBusReceiveMode.RECEIVE_AND_DELETE, consumerProperties.getReceiveMode());
}
@Test
void maxAutoLockRenewDurationDefaults() {
assertEquals(Duration.ofMinutes(5), consumerProperties.getMaxAutoLockRenewDuration());
}
@Test
void customMaxAutoLockRenewDuration() {
Duration duration = Duration.ofMinutes(6);
consumerProperties.setMaxAutoLockRenewDuration(duration);
assertEquals(duration, consumerProperties.getMaxAutoLockRenewDuration());
}
} |
we should call this out in changelog. | public Mono<Void> uploadFromFile(String filePath, boolean overwrite) {
try {
Mono<Void> overwriteCheck = Mono.empty();
BlobRequestConditions requestConditions = null;
if (!overwrite) {
if (UploadUtils.shouldUploadInChunks(filePath,
(long) BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES, logger)) {
overwriteCheck = exists().flatMap(exists -> exists
? monoError(logger, new IllegalArgumentException(Constants.BLOB_ALREADY_EXISTS))
: Mono.empty());
}
requestConditions = new BlobRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return overwriteCheck.then(uploadFromFile(filePath, null, null, null, null, requestConditions));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
} | (long) BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES, logger)) { | public Mono<Void> uploadFromFile(String filePath, boolean overwrite) {
Mono<Void> overwriteCheck = Mono.empty();
BlobRequestConditions requestConditions = null;
if (!overwrite) {
if (UploadUtils.shouldUploadInChunks(filePath, ModelHelper.BLOB_DEFAULT_MAX_SINGLE_UPLOAD_SIZE, LOGGER)) {
overwriteCheck = exists().flatMap(exists -> exists
? monoError(LOGGER, new IllegalArgumentException(Constants.BLOB_ALREADY_EXISTS))
: Mono.empty());
}
requestConditions = new BlobRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return overwriteCheck.then(uploadFromFile(filePath, null, null, null, null, requestConditions));
} | class BlobAsyncClient extends BlobAsyncClientBase {
/**
* The block size to use if none is specified in parallel operations.
*/
public static final int BLOB_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB;
/**
* The number of buffers to use if none is specified on the buffered upload method.
*/
public static final int BLOB_DEFAULT_NUMBER_OF_BUFFERS = 8;
/**
* If a blob is known to be greater than 100MB, using a larger block size will trigger some server-side
* optimizations. If the block size is not set and the size of the blob is known to be greater than 100MB, this
* value will be used.
*/
public static final int BLOB_DEFAULT_HTBB_UPLOAD_BLOCK_SIZE = 8 * Constants.MB;
static final long BLOB_MAX_UPLOAD_BLOCK_SIZE = 4000L * Constants.MB;
private final ClientLogger logger = new ClientLogger(BlobAsyncClient.class);
private BlockBlobAsyncClient blockBlobAsyncClient;
private AppendBlobAsyncClient appendBlobAsyncClient;
private PageBlobAsyncClient pageBlobAsyncClient;
/**
* Protected constructor for use by {@link BlobClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param containerName The container name.
* @param blobName The blob name.
* @param snapshot The snapshot identifier for the blob, pass {@code null} to interact with the blob directly.
* @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
*/
protected BlobAsyncClient(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName,
String containerName, String blobName, String snapshot, CpkInfo customerProvidedKey) {
super(pipeline, url, serviceVersion, accountName, containerName, blobName, snapshot, customerProvidedKey);
}
/**
* Protected constructor for use by {@link BlobClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param containerName The container name.
* @param blobName The blob name.
* @param snapshot The snapshot identifier for the blob, pass {@code null} to interact with the blob directly.
* @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param encryptionScope Encryption scope used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
*/
protected BlobAsyncClient(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName,
String containerName, String blobName, String snapshot, CpkInfo customerProvidedKey,
EncryptionScope encryptionScope) {
super(pipeline, url, serviceVersion, accountName, containerName, blobName, snapshot, customerProvidedKey,
encryptionScope);
}
/**
* Protected constructor for use by {@link BlobClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param containerName The container name.
* @param blobName The blob name.
* @param snapshot The snapshot identifier for the blob, pass {@code null} to interact with the blob directly.
* @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param encryptionScope Encryption scope used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param versionId The version identifier for the blob, pass {@code null} to interact with the latest blob version.
*/
protected BlobAsyncClient(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName,
String containerName, String blobName, String snapshot, CpkInfo customerProvidedKey,
EncryptionScope encryptionScope, String versionId) {
super(pipeline, url, serviceVersion, accountName, containerName, blobName, snapshot, customerProvidedKey,
encryptionScope, versionId);
}
/**
* Creates a new {@link BlobAsyncClient} linked to the {@code snapshot} of this blob resource.
*
* @param snapshot the identifier for a specific snapshot of this blob
* @return A {@link BlobAsyncClient} used to interact with the specific snapshot.
*/
@Override
public BlobAsyncClient getSnapshotClient(String snapshot) {
return new BlobAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(),
getContainerName(), getBlobName(), snapshot, getCustomerProvidedKey(), encryptionScope, getVersionId());
}
/**
* Creates a new {@link BlobAsyncClient} linked to the {@code versionId} of this blob resource.
*
* @param versionId the identifier for a specific version of this blob,
* pass {@code null} to interact with the latest blob version.
* @return A {@link BlobAsyncClient} used to interact with the specific version.
*/
@Override
public BlobAsyncClient getVersionClient(String versionId) {
return new BlobAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(),
getContainerName(), getBlobName(), getSnapshotId(), getCustomerProvidedKey(), encryptionScope, versionId);
}
/**
* Creates a new {@link BlobAsyncClient} with the specified {@code encryptionScope}.
*
* @param encryptionScope the encryption scope for the blob, pass {@code null} to use no encryption scope.
* @return a {@link BlobAsyncClient} with the specified {@code encryptionScope}.
*/
@Override
public BlobAsyncClient getEncryptionScopeAsyncClient(String encryptionScope) {
EncryptionScope finalEncryptionScope = null;
if (encryptionScope != null) {
finalEncryptionScope = new EncryptionScope().setEncryptionScope(encryptionScope);
}
return new BlobAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(),
getContainerName(), getBlobName(), getSnapshotId(), getCustomerProvidedKey(), finalEncryptionScope,
getVersionId());
}
/**
* Creates a new {@link BlobAsyncClient} with the specified {@code customerProvidedKey}.
*
* @param customerProvidedKey the {@link CustomerProvidedKey} for the blob,
* pass {@code null} to use no customer provided key.
* @return a {@link BlobAsyncClient} with the specified {@code customerProvidedKey}.
*/
@Override
public BlobAsyncClient getCustomerProvidedKeyAsyncClient(CustomerProvidedKey customerProvidedKey) {
CpkInfo finalCustomerProvidedKey = null;
if (customerProvidedKey != null) {
finalCustomerProvidedKey = new CpkInfo()
.setEncryptionKey(customerProvidedKey.getKey())
.setEncryptionKeySha256(customerProvidedKey.getKeySha256())
.setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm());
}
return new BlobAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(),
getContainerName(), getBlobName(), getSnapshotId(), finalCustomerProvidedKey, encryptionScope,
getVersionId());
}
/**
* Creates a new {@link AppendBlobAsyncClient} associated with this blob.
*
* @return A {@link AppendBlobAsyncClient} associated with this blob.
*/
public AppendBlobAsyncClient getAppendBlobAsyncClient() {
if (appendBlobAsyncClient == null) {
appendBlobAsyncClient = prepareBuilder().buildAppendBlobAsyncClient();
}
return appendBlobAsyncClient;
}
/**
* Creates a new {@link BlockBlobAsyncClient} associated with this blob.
*
* @return A {@link BlockBlobAsyncClient} associated with this blob.
*/
public BlockBlobAsyncClient getBlockBlobAsyncClient() {
if (blockBlobAsyncClient == null) {
blockBlobAsyncClient = prepareBuilder().buildBlockBlobAsyncClient();
}
return blockBlobAsyncClient;
}
/**
* Creates a new {@link PageBlobAsyncClient} associated with this blob.
*
* @return A {@link PageBlobAsyncClient} associated with this blob.
*/
public PageBlobAsyncClient getPageBlobAsyncClient() {
if (pageBlobAsyncClient == null) {
pageBlobAsyncClient = prepareBuilder().buildPageBlobAsyncClient();
}
return pageBlobAsyncClient;
}
private SpecializedBlobClientBuilder prepareBuilder() {
SpecializedBlobClientBuilder builder = new SpecializedBlobClientBuilder()
.pipeline(getHttpPipeline())
.endpoint(getBlobUrl())
.snapshot(getSnapshotId())
.serviceVersion(getServiceVersion());
CpkInfo cpk = getCustomerProvidedKey();
if (cpk != null) {
builder.customerProvidedKey(new CustomerProvidedKey(cpk.getEncryptionKey()));
}
if (encryptionScope != null) {
builder.encryptionScope(encryptionScope.getEncryptionScope());
}
return builder;
}
/**
* Creates a new block blob. By default this method will not overwrite an existing blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with this method; the content of the existing blob is overwritten with the new content. To perform a partial
* update of a block blob's, use {@link BlockBlobAsyncClient
* BlockBlobAsyncClient
* <a href="https:
* <a href="https:
* <p>
* The data passed need not support multiple subscriptions/be replayable as is required in other upload methods when
* retries are enabled, and the length of the data need not be known in advance. Therefore, this method does
* support uploading any arbitrary data source, including network streams. This behavior is possible because this
* method will perform some internal buffering as configured by the blockSize and numBuffers parameters, so while
* this method may offer additional convenience, it will not be as performant as other options, which should be
* preferred when possible.
* <p>
* Typically, the greater the number of buffers used, the greater the possible parallelism when transferring the
* data. Larger buffers means we will have to stage fewer blocks and therefore require fewer IO operations. The
* trade-offs between these values are context-dependent, so some experimentation may be required to optimize inputs
* for a given scenario.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.upload
* <pre>
* ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions&
* .setBlockSizeLong&
* .setMaxConcurrency&
* client.upload&
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.upload
*
* @param data The data to write to the blob. Unlike other upload methods, this method does not require that the
* {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected
* to produce the same values across subscriptions.
* @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading.
* @return A reactive response containing the information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlockBlobItem> upload(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions) {
try {
return upload(data, parallelTransferOptions, false);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with this method; the content of the existing blob is overwritten with the new content. To perform a partial
* update of a block blob's, use {@link BlockBlobAsyncClient
* BlockBlobAsyncClient
* <a href="https:
* <a href="https:
* <p>
* The data passed need not support multiple subscriptions/be replayable as is required in other upload methods when
* retries are enabled, and the length of the data need not be known in advance. Therefore, this method does
* support uploading any arbitrary data source, including network streams. This behavior is possible because this
* method will perform some internal buffering as configured by the blockSize and numBuffers parameters, so while
* this method may offer additional convenience, it will not be as performant as other options, which should be
* preferred when possible.
* <p>
* Typically, the greater the number of buffers used, the greater the possible parallelism when transferring the
* data. Larger buffers means we will have to stage fewer blocks and therefore require fewer IO operations. The
* trade-offs between these values are context-dependent, so some experimentation may be required to optimize inputs
* for a given scenario.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.upload
* <pre>
* ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions&
* .setBlockSizeLong&
* .setMaxConcurrency&
* boolean overwrite = false; &
* client.upload&
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.upload
*
* @param data The data to write to the blob. Unlike other upload methods, this method does not require that the
* {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected
* to produce the same values across subscriptions.
* @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading.
* @param overwrite Whether or not to overwrite, should the blob already exist.
* @return A reactive response containing the information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlockBlobItem> upload(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions,
boolean overwrite) {
try {
Mono<Void> overwriteCheck;
BlobRequestConditions requestConditions;
if (overwrite) {
overwriteCheck = Mono.empty();
requestConditions = null;
} else {
overwriteCheck = exists().flatMap(exists -> exists
? monoError(logger, new IllegalArgumentException(Constants.BLOB_ALREADY_EXISTS))
: Mono.empty());
requestConditions = new BlobRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return overwriteCheck
.then(uploadWithResponse(data, parallelTransferOptions, null, null, null,
requestConditions)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new block blob. By default this method will not overwrite an existing blob.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.upload
* <pre>
* client.upload&
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.upload
*
* @param data The data to write to the blob.
* @return A reactive response containing the information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlockBlobItem> upload(BinaryData data) {
try {
return upload(data, false);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.upload
* <pre>
* boolean overwrite = false; &
* client.upload&
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.upload
*
* @param data The data to write to the blob.
* @param overwrite Whether or not to overwrite, should the blob already exist.
* @return A reactive response containing the information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlockBlobItem> upload(BinaryData data,
boolean overwrite) {
try {
Mono<Void> overwriteCheck;
BlobRequestConditions requestConditions;
if (overwrite) {
overwriteCheck = Mono.empty();
requestConditions = null;
} else {
overwriteCheck = exists().flatMap(exists -> exists
? monoError(logger, new IllegalArgumentException(Constants.BLOB_ALREADY_EXISTS))
: Mono.empty());
requestConditions = new BlobRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return overwriteCheck
.then(uploadWithResponse(Flux.just(data.toByteBuffer()), null, null, null, null,
requestConditions)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with this method; the content of the existing blob is overwritten with the new content. To perform a partial
* update of a block blob's, use {@link BlockBlobAsyncClient
* BlockBlobAsyncClient
* <a href="https:
* <a href="https:
* <p>
* The data passed need not support multiple subscriptions/be replayable as is required in other upload methods when
* retries are enabled, and the length of the data need not be known in advance. Therefore, this method does
* support uploading any arbitrary data source, including network streams. This behavior is possible because this
* method will perform some internal buffering as configured by the blockSize and numBuffers parameters, so while
* this method may offer additional convenience, it will not be as performant as other options, which should be
* preferred when possible.
* <p>
* Typically, the greater the number of buffers used, the greater the possible parallelism when transferring the
* data. Larger buffers means we will have to stage fewer blocks and therefore require fewer IO operations. The
* trade-offs between these values are context-dependent, so some experimentation may be required to optimize inputs
* for a given scenario.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.uploadWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
*
* ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions&
* .setBlockSizeLong&
* .setMaxConcurrency&
*
* client.uploadWithResponse&
* .subscribe&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.uploadWithResponse
*
* <p><strong>Using Progress Reporting</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.uploadWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
*
* ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions&
* .setBlockSizeLong&
* .setMaxConcurrency&
* .setProgressReceiver&
*
* client.uploadWithResponse&
* .subscribe&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.uploadWithResponse
*
* @param data The data to write to the blob. Unlike other upload methods, this method does not require that the
* {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected
* to produce the same values across subscriptions.
* @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading.
* @param headers {@link BlobHttpHeaders}
* @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param tier {@link AccessTier} for the destination blob.
* @param requestConditions {@link BlobRequestConditions}
* @return A reactive response containing the information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlockBlobItem>> uploadWithResponse(Flux<ByteBuffer> data,
ParallelTransferOptions parallelTransferOptions, BlobHttpHeaders headers, Map<String, String> metadata,
AccessTier tier, BlobRequestConditions requestConditions) {
return this.uploadWithResponse(new BlobParallelUploadOptions(data)
.setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata).setTier(tier)
.setRequestConditions(requestConditions));
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with this method; the content of the existing blob is overwritten with the new content. To perform a partial
* update of a block blob's, use {@link BlockBlobAsyncClient
* BlockBlobAsyncClient
* <a href="https:
* <a href="https:
* <p>
* The data passed need not support multiple subscriptions/be replayable as is required in other upload methods when
* retries are enabled, and the length of the data need not be known in advance. Therefore, this method does
* support uploading any arbitrary data source, including network streams. This behavior is possible because this
* method will perform some internal buffering as configured by the blockSize and numBuffers parameters, so while
* this method may offer additional convenience, it will not be as performant as other options, which should be
* preferred when possible.
* <p>
* Typically, the greater the number of buffers used, the greater the possible parallelism when transferring the
* data. Larger buffers means we will have to stage fewer blocks and therefore require fewer IO operations. The
* trade-offs between these values are context-dependent, so some experimentation may be required to optimize inputs
* for a given scenario.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.uploadWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
*
* ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions&
* .setMaxConcurrency&
* System.out.printf&
*
* client.uploadWithResponse&
* .setParallelTransferOptions&
* .setTier&
* .subscribe&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.uploadWithResponse
*
* <p><strong>Using Progress Reporting</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.uploadWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
*
* ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions&
* .setMaxConcurrency&
* System.out.printf&
*
* client.uploadWithResponse&
* .setParallelTransferOptions&
* .setTier&
* .subscribe&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.uploadWithResponse
*
* @param options {@link BlobParallelUploadOptions}. Unlike other upload methods, this method does not require that
* the {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not
* expected to produce the same values across subscriptions.
* @return A reactive response containing the information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlockBlobItem>> uploadWithResponse(BlobParallelUploadOptions options) {
/*
The following is catalogue of all the places we allocate memory/copy in any upload method a justifaction for
that case current as of 1/13/21.
- Async buffered upload chunked upload: We used an UploadBufferPool. This will allocate memory as needed up to
the configured maximum. This is necessary to support replayability on retires. Each flux to come out of the pool
is a Flux.just() of up to two deep copied buffers, so it is replayable. It also allows us to optimize the upload
by uploading the maximum amount per block. Finally, in the case of chunked uploading, it allows the customer to
pass data without knowing the size. Note that full upload does not need a deep copy because the Flux emitted by
the PayloadSizeGate in the full upload case is already replayable and the length is maintained by the gate.
- Sync buffered upload: converting the input stream to a flux involves creating a buffer for each stream read.
Using a new buffer per read ensures that the reads are safe and not overwriting data in buffers that were passed
to the async upload but have not yet been sent. This covers both full and chunked uploads in the sync case.
- BlobOutputStream: A deep copy is made of any buffer passed to write. While async copy does streamline our code
and allow for some potential parallelization, this extra copy is necessary to ensure that customers writing to
the stream in a tight loop are not overwriting data previously given to the stream before it has been sent.
Taken together, these should support retries and protect against data being overwritten in all upload scenarios.
One note is that there is no deep copy in the uploadFull method. This is unnecessary as explained in
uploadFullOrChunked because the Flux coming out of the size gate in that case is already replayable and reusing
buffers is not a common scenario for async like it is in sync (and we already buffer in sync to convert from a
stream).
*/
try {
StorageImplUtils.assertNotNull("options", options);
final ParallelTransferOptions parallelTransferOptions =
ModelHelper.populateAndApplyDefaults(options.getParallelTransferOptions());
final BlobHttpHeaders headers = options.getHeaders();
final Map<String, String> metadata = options.getMetadata();
final Map<String, String> tags = options.getTags();
final AccessTier tier = options.getTier();
final BlobRequestConditions requestConditions = options.getRequestConditions() == null
? new BlobRequestConditions() : options.getRequestConditions();
final boolean computeMd5 = options.isComputeMd5();
final BlobImmutabilityPolicy immutabilityPolicy = options.getImmutabilityPolicy() == null
? new BlobImmutabilityPolicy() : options.getImmutabilityPolicy();
final Boolean legalHold = options.isLegalHold();
BlockBlobAsyncClient blockBlobAsyncClient = getBlockBlobAsyncClient();
Function<Flux<ByteBuffer>, Mono<Response<BlockBlobItem>>> uploadInChunksFunction = (stream) ->
uploadInChunks(blockBlobAsyncClient, stream, parallelTransferOptions, headers, metadata, tags,
tier, requestConditions, computeMd5, immutabilityPolicy, legalHold);
BiFunction<Flux<ByteBuffer>, Long, Mono<Response<BlockBlobItem>>> uploadFullBlobFunction =
(stream, length) -> uploadFullBlob(blockBlobAsyncClient, stream, length, parallelTransferOptions,
headers, metadata, tags, tier, requestConditions, computeMd5, immutabilityPolicy, legalHold);
Flux<ByteBuffer> data = options.getDataFlux();
if (data == null && options.getOptionalLength() == null) {
int chunkSize = (int) Math.min(Constants.MAX_INPUT_STREAM_CONVERTER_BUFFER_LENGTH,
parallelTransferOptions.getBlockSizeLong());
data = FluxUtil.toFluxByteBuffer(options.getDataStream(), chunkSize);
} else if (data == null) {
int chunkSize = (int) Math.min(Constants.MAX_INPUT_STREAM_CONVERTER_BUFFER_LENGTH,
parallelTransferOptions.getBlockSizeLong());
data = Utility.convertStreamToByteBuffer(
options.getDataStream(), options.getOptionalLength(), chunkSize, false);
}
return UploadUtils.uploadFullOrChunked(data, ModelHelper.wrapBlobOptions(parallelTransferOptions),
uploadInChunksFunction, uploadFullBlobFunction);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private Mono<Response<BlockBlobItem>> uploadFullBlob(BlockBlobAsyncClient blockBlobAsyncClient,
Flux<ByteBuffer> data, long length, ParallelTransferOptions parallelTransferOptions, BlobHttpHeaders headers,
Map<String, String> metadata, Map<String, String> tags, AccessTier tier,
BlobRequestConditions requestConditions, boolean computeMd5, BlobImmutabilityPolicy immutabilityPolicy,
Boolean legalHold) {
/*
Note that there is no need to buffer here as the flux returned by the size gate in this case is created
from an iterable and is therefore replayable.
*/
Flux<ByteBuffer> progressData = ProgressReporter.addProgressReporting(data,
parallelTransferOptions.getProgressReceiver());
return UploadUtils.computeMd5(progressData, computeMd5, logger)
.map(fluxMd5Wrapper -> new BlockBlobSimpleUploadOptions(fluxMd5Wrapper.getData(), length)
.setHeaders(headers)
.setMetadata(metadata)
.setTags(tags)
.setTier(tier)
.setRequestConditions(requestConditions)
.setContentMd5(fluxMd5Wrapper.getMd5())
.setImmutabilityPolicy(immutabilityPolicy)
.setLegalHold(legalHold))
.flatMap(blockBlobAsyncClient::uploadWithResponse);
}
private Mono<Response<BlockBlobItem>> uploadInChunks(BlockBlobAsyncClient blockBlobAsyncClient,
Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions, BlobHttpHeaders headers,
Map<String, String> metadata, Map<String, String> tags, AccessTier tier,
BlobRequestConditions requestConditions, boolean computeMd5, BlobImmutabilityPolicy immutabilityPolicy,
Boolean legalHold) {
AtomicLong totalProgress = new AtomicLong();
Lock progressLock = new ReentrantLock();
BufferStagingArea stagingArea = new BufferStagingArea(parallelTransferOptions.getBlockSizeLong(),
BlockBlobClient.MAX_STAGE_BLOCK_BYTES_LONG);
Flux<ByteBuffer> chunkedSource = UploadUtils.chunkSource(data,
ModelHelper.wrapBlobOptions(parallelTransferOptions));
/*
Write to the pool and upload the output.
maxConcurrency = 1 when writing means only 1 BufferAggregator will be accumulating at a time.
parallelTransferOptions.getMaxConcurrency() appends will be happening at once, so we guarantee buffering of
only concurrency + 1 chunks at a time.
*/
return chunkedSource.flatMapSequential(stagingArea::write, 1, 1)
.concatWith(Flux.defer(stagingArea::flush))
.flatMapSequential(bufferAggregator -> {
Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting(
bufferAggregator.asFlux(),
parallelTransferOptions.getProgressReceiver(),
progressLock,
totalProgress);
final String blockId = Base64.getEncoder().encodeToString(UUID.randomUUID().toString().getBytes(UTF_8));
return UploadUtils.computeMd5(progressData, computeMd5, logger)
.flatMap(fluxMd5Wrapper -> blockBlobAsyncClient.stageBlockWithResponse(blockId,
fluxMd5Wrapper.getData(), bufferAggregator.length(), fluxMd5Wrapper.getMd5(),
requestConditions.getLeaseId()))
.map(x -> blockId)
.flux();
}, parallelTransferOptions.getMaxConcurrency(), 1)
.collect(Collectors.toList())
.flatMap(ids ->
blockBlobAsyncClient.commitBlockListWithResponse(new BlockBlobCommitBlockListOptions(ids)
.setHeaders(headers).setMetadata(metadata).setTags(tags).setTier(tier)
.setRequestConditions(requestConditions).setImmutabilityPolicy(immutabilityPolicy)
.setLegalHold(legalHold)));
}
/**
* Creates a new block blob with the content of the specified file. By default this method will not overwrite an
* existing blob.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.uploadFromFile
* <pre>
* client.uploadFromFile&
* .doOnError&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.uploadFromFile
*
* @param filePath Path to the upload file
* @return An empty response
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> uploadFromFile(String filePath) {
try {
return uploadFromFile(filePath, false);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new block blob, or updates the content of an existing block blob, with the content of the specified
* file.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.uploadFromFile
* <pre>
* boolean overwrite = false; &
* client.uploadFromFile&
* .doOnError&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.uploadFromFile
*
* @param filePath Path to the upload file
* @param overwrite Whether or not to overwrite, should the blob already exist.
* @return An empty response
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Creates a new block blob, or updates the content of an existing block blob, with the content of the specified
* file.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.uploadFromFile
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
*
* client.uploadFromFile&
* new ParallelTransferOptions&
* headers, metadata, AccessTier.HOT, requestConditions&
* .doOnError&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.uploadFromFile
*
* @param filePath Path to the upload file
* @param parallelTransferOptions {@link ParallelTransferOptions} to use to upload from file. Number of parallel
* transfers parameter is ignored.
* @param headers {@link BlobHttpHeaders}
* @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param tier {@link AccessTier} for the destination blob.
* @param requestConditions {@link BlobRequestConditions}
* @return An empty response
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> uploadFromFile(String filePath, ParallelTransferOptions parallelTransferOptions,
BlobHttpHeaders headers, Map<String, String> metadata, AccessTier tier,
BlobRequestConditions requestConditions) {
return this.uploadFromFileWithResponse(new BlobUploadFromFileOptions(filePath)
.setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata)
.setTier(tier).setRequestConditions(requestConditions))
.then();
}
/**
* Creates a new block blob, or updates the content of an existing block blob, with the content of the specified
* file.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.uploadFromFileWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
*
* client.uploadFromFileWithResponse&
* .setParallelTransferOptions&
* new ParallelTransferOptions&
* .setHeaders&
* .setRequestConditions&
* .doOnError&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.uploadFromFileWithResponse
*
* @param options {@link BlobUploadFromFileOptions}
* @return A reactive response containing the information of the uploaded block blob.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlockBlobItem>> uploadFromFileWithResponse(BlobUploadFromFileOptions options) {
StorageImplUtils.assertNotNull("options", options);
Long originalBlockSize = (options.getParallelTransferOptions() == null)
? null
: options.getParallelTransferOptions().getBlockSizeLong();
final ParallelTransferOptions finalParallelTransferOptions =
ModelHelper.populateAndApplyDefaults(options.getParallelTransferOptions());
try {
return Mono.using(() -> UploadUtils.uploadFileResourceSupplier(options.getFilePath(), logger),
channel -> {
try {
BlockBlobAsyncClient blockBlobAsyncClient = getBlockBlobAsyncClient();
long fileSize = channel.size();
if (UploadUtils.shouldUploadInChunks(options.getFilePath(),
finalParallelTransferOptions.getMaxSingleUploadSizeLong(), logger)) {
return uploadFileChunks(fileSize, finalParallelTransferOptions, originalBlockSize,
options.getHeaders(), options.getMetadata(), options.getTags(),
options.getTier(), options.getRequestConditions(), channel,
blockBlobAsyncClient);
} else {
Flux<ByteBuffer> data = FluxUtil.readFile(channel);
if (finalParallelTransferOptions.getProgressReceiver() != null) {
data = ProgressReporter.addProgressReporting(data,
finalParallelTransferOptions.getProgressReceiver());
}
return blockBlobAsyncClient.uploadWithResponse(
new BlockBlobSimpleUploadOptions(data, fileSize).setHeaders(options.getHeaders())
.setMetadata(options.getMetadata()).setTags(options.getTags())
.setTier(options.getTier())
.setRequestConditions(options.getRequestConditions()));
}
} catch (IOException ex) {
return Mono.error(ex);
}
},
channel ->
UploadUtils.uploadFileCleanup(channel, logger));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private Mono<Response<BlockBlobItem>> uploadFileChunks(
long fileSize, ParallelTransferOptions parallelTransferOptions,
Long originalBlockSize, BlobHttpHeaders headers, Map<String, String> metadata, Map<String, String> tags,
AccessTier tier, BlobRequestConditions requestConditions, AsynchronousFileChannel channel,
BlockBlobAsyncClient client) {
final BlobRequestConditions finalRequestConditions = (requestConditions == null)
? new BlobRequestConditions() : requestConditions;
AtomicLong totalProgress = new AtomicLong();
Lock progressLock = new ReentrantLock();
final SortedMap<Long, String> blockIds = new TreeMap<>();
return Flux.fromIterable(sliceFile(fileSize, originalBlockSize, parallelTransferOptions.getBlockSizeLong()))
.flatMap(chunk -> {
String blockId = getBlockID();
blockIds.put(chunk.getOffset(), blockId);
Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting(
FluxUtil.readFile(channel, chunk.getOffset(), chunk.getCount()),
parallelTransferOptions.getProgressReceiver(), progressLock, totalProgress);
return client.stageBlockWithResponse(blockId, progressData, chunk.getCount(), null,
finalRequestConditions.getLeaseId());
}, parallelTransferOptions.getMaxConcurrency())
.then(Mono.defer(() -> client.commitBlockListWithResponse(
new BlockBlobCommitBlockListOptions(new ArrayList<>(blockIds.values()))
.setHeaders(headers).setMetadata(metadata).setTags(tags).setTier(tier)
.setRequestConditions(finalRequestConditions))));
}
/**
* RESERVED FOR INTERNAL USE.
*
* Resource Supplier for UploadFile.
*
* @param filePath The path for the file
* @return {@code AsynchronousFileChannel}
* @throws UncheckedIOException an input output exception.
* @deprecated due to refactoring code to be in the common storage library.
*/
@Deprecated
protected AsynchronousFileChannel uploadFileResourceSupplier(String filePath) {
return UploadUtils.uploadFileResourceSupplier(filePath, logger);
}
private String getBlockID() {
return Base64.getEncoder().encodeToString(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));
}
private List<BlobRange> sliceFile(long fileSize, Long originalBlockSize, long blockSize) {
List<BlobRange> ranges = new ArrayList<>();
if (fileSize > 100 * Constants.MB && originalBlockSize == null) {
blockSize = BLOB_DEFAULT_HTBB_UPLOAD_BLOCK_SIZE;
}
for (long pos = 0; pos < fileSize; pos += blockSize) {
long count = blockSize;
if (pos + count > fileSize) {
count = fileSize - pos;
}
ranges.add(new BlobRange(pos, count));
}
return ranges;
}
} | class BlobAsyncClient extends BlobAsyncClientBase {
/**
* The block size to use if none is specified in parallel operations.
*/
public static final int BLOB_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB;
/**
* The number of buffers to use if none is specified on the buffered upload method.
*/
public static final int BLOB_DEFAULT_NUMBER_OF_BUFFERS = 8;
/**
* If a blob is known to be greater than 100MB, using a larger block size will trigger some server-side
* optimizations. If the block size is not set and the size of the blob is known to be greater than 100MB, this
* value will be used.
*/
public static final int BLOB_DEFAULT_HTBB_UPLOAD_BLOCK_SIZE = 8 * Constants.MB;
static final long BLOB_MAX_UPLOAD_BLOCK_SIZE = 4000L * Constants.MB;
private static final ClientLogger LOGGER = new ClientLogger(BlobAsyncClient.class);
private BlockBlobAsyncClient blockBlobAsyncClient;
private AppendBlobAsyncClient appendBlobAsyncClient;
private PageBlobAsyncClient pageBlobAsyncClient;
/**
* Protected constructor for use by {@link BlobClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param containerName The container name.
* @param blobName The blob name.
* @param snapshot The snapshot identifier for the blob, pass {@code null} to interact with the blob directly.
* @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
*/
protected BlobAsyncClient(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName,
String containerName, String blobName, String snapshot, CpkInfo customerProvidedKey) {
super(pipeline, url, serviceVersion, accountName, containerName, blobName, snapshot, customerProvidedKey);
}
/**
* Protected constructor for use by {@link BlobClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param containerName The container name.
* @param blobName The blob name.
* @param snapshot The snapshot identifier for the blob, pass {@code null} to interact with the blob directly.
* @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param encryptionScope Encryption scope used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
*/
protected BlobAsyncClient(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName,
String containerName, String blobName, String snapshot, CpkInfo customerProvidedKey,
EncryptionScope encryptionScope) {
super(pipeline, url, serviceVersion, accountName, containerName, blobName, snapshot, customerProvidedKey,
encryptionScope);
}
/**
* Protected constructor for use by {@link BlobClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param containerName The container name.
* @param blobName The blob name.
* @param snapshot The snapshot identifier for the blob, pass {@code null} to interact with the blob directly.
* @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param encryptionScope Encryption scope used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param versionId The version identifier for the blob, pass {@code null} to interact with the latest blob version.
*/
protected BlobAsyncClient(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName,
String containerName, String blobName, String snapshot, CpkInfo customerProvidedKey,
EncryptionScope encryptionScope, String versionId) {
super(pipeline, url, serviceVersion, accountName, containerName, blobName, snapshot, customerProvidedKey,
encryptionScope, versionId);
}
/**
* Creates a new {@link BlobAsyncClient} linked to the {@code snapshot} of this blob resource.
*
* @param snapshot the identifier for a specific snapshot of this blob
* @return A {@link BlobAsyncClient} used to interact with the specific snapshot.
*/
@Override
public BlobAsyncClient getSnapshotClient(String snapshot) {
return new BlobAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(),
getContainerName(), getBlobName(), snapshot, getCustomerProvidedKey(), encryptionScope, getVersionId());
}
/**
* Creates a new {@link BlobAsyncClient} linked to the {@code versionId} of this blob resource.
*
* @param versionId the identifier for a specific version of this blob,
* pass {@code null} to interact with the latest blob version.
* @return A {@link BlobAsyncClient} used to interact with the specific version.
*/
@Override
public BlobAsyncClient getVersionClient(String versionId) {
return new BlobAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(),
getContainerName(), getBlobName(), getSnapshotId(), getCustomerProvidedKey(), encryptionScope, versionId);
}
/**
* Creates a new {@link BlobAsyncClient} with the specified {@code encryptionScope}.
*
* @param encryptionScope the encryption scope for the blob, pass {@code null} to use no encryption scope.
* @return a {@link BlobAsyncClient} with the specified {@code encryptionScope}.
*/
@Override
public BlobAsyncClient getEncryptionScopeAsyncClient(String encryptionScope) {
EncryptionScope finalEncryptionScope = null;
if (encryptionScope != null) {
finalEncryptionScope = new EncryptionScope().setEncryptionScope(encryptionScope);
}
return new BlobAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(),
getContainerName(), getBlobName(), getSnapshotId(), getCustomerProvidedKey(), finalEncryptionScope,
getVersionId());
}
/**
* Creates a new {@link BlobAsyncClient} with the specified {@code customerProvidedKey}.
*
* @param customerProvidedKey the {@link CustomerProvidedKey} for the blob,
* pass {@code null} to use no customer provided key.
* @return a {@link BlobAsyncClient} with the specified {@code customerProvidedKey}.
*/
@Override
public BlobAsyncClient getCustomerProvidedKeyAsyncClient(CustomerProvidedKey customerProvidedKey) {
CpkInfo finalCustomerProvidedKey = null;
if (customerProvidedKey != null) {
finalCustomerProvidedKey = new CpkInfo()
.setEncryptionKey(customerProvidedKey.getKey())
.setEncryptionKeySha256(customerProvidedKey.getKeySha256())
.setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm());
}
return new BlobAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(),
getContainerName(), getBlobName(), getSnapshotId(), finalCustomerProvidedKey, encryptionScope,
getVersionId());
}
/**
* Creates a new {@link AppendBlobAsyncClient} associated with this blob.
*
* @return A {@link AppendBlobAsyncClient} associated with this blob.
*/
public AppendBlobAsyncClient getAppendBlobAsyncClient() {
if (appendBlobAsyncClient == null) {
appendBlobAsyncClient = prepareBuilder().buildAppendBlobAsyncClient();
}
return appendBlobAsyncClient;
}
/**
* Creates a new {@link BlockBlobAsyncClient} associated with this blob.
*
* @return A {@link BlockBlobAsyncClient} associated with this blob.
*/
public BlockBlobAsyncClient getBlockBlobAsyncClient() {
if (blockBlobAsyncClient == null) {
blockBlobAsyncClient = prepareBuilder().buildBlockBlobAsyncClient();
}
return blockBlobAsyncClient;
}
/**
* Creates a new {@link PageBlobAsyncClient} associated with this blob.
*
* @return A {@link PageBlobAsyncClient} associated with this blob.
*/
public PageBlobAsyncClient getPageBlobAsyncClient() {
if (pageBlobAsyncClient == null) {
pageBlobAsyncClient = prepareBuilder().buildPageBlobAsyncClient();
}
return pageBlobAsyncClient;
}
private SpecializedBlobClientBuilder prepareBuilder() {
SpecializedBlobClientBuilder builder = new SpecializedBlobClientBuilder()
.pipeline(getHttpPipeline())
.endpoint(getBlobUrl())
.snapshot(getSnapshotId())
.serviceVersion(getServiceVersion());
CpkInfo cpk = getCustomerProvidedKey();
if (cpk != null) {
builder.customerProvidedKey(new CustomerProvidedKey(cpk.getEncryptionKey()));
}
if (encryptionScope != null) {
builder.encryptionScope(encryptionScope.getEncryptionScope());
}
return builder;
}
/**
* Creates a new block blob. By default, this method will not overwrite an existing blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with this method; the content of the existing blob is overwritten with the new content. To perform a partial
* update of a block blob's, use {@link BlockBlobAsyncClient
* BlockBlobAsyncClient
* <a href="https:
* <a href="https:
* <p>
* The data passed need not support multiple subscriptions/be replayable as is required in other upload methods when
* retries are enabled, and the length of the data need not be known in advance. Therefore, this method does
* support uploading any arbitrary data source, including network streams. This behavior is possible because this
* method will perform some internal buffering as configured by the blockSize and numBuffers parameters, so while
* this method may offer additional convenience, it will not be as performant as other options, which should be
* preferred when possible.
* <p>
* Typically, the greater the number of buffers used, the greater the possible parallelism when transferring the
* data. Larger buffers means we will have to stage fewer blocks and therefore require fewer IO operations. The
* trade-offs between these values are context-dependent, so some experimentation may be required to optimize inputs
* for a given scenario.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.upload
* <pre>
* ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions&
* .setBlockSizeLong&
* .setMaxConcurrency&
* client.upload&
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.upload
*
* @param data The data to write to the blob. Unlike other upload methods, this method does not require that the
* {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected
* to produce the same values across subscriptions.
* @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading.
* @return A reactive response containing the information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlockBlobItem> upload(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions) {
return upload(data, parallelTransferOptions, false);
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with this method; the content of the existing blob is overwritten with the new content. To perform a partial
* update of a block blob's, use {@link BlockBlobAsyncClient
* BlockBlobAsyncClient
* <a href="https:
* <a href="https:
* <p>
* The data passed need not support multiple subscriptions/be replayable as is required in other upload methods when
* retries are enabled, and the length of the data need not be known in advance. Therefore, this method does
* support uploading any arbitrary data source, including network streams. This behavior is possible because this
* method will perform some internal buffering as configured by the blockSize and numBuffers parameters, so while
* this method may offer additional convenience, it will not be as performant as other options, which should be
* preferred when possible.
* <p>
* Typically, the greater the number of buffers used, the greater the possible parallelism when transferring the
* data. Larger buffers means we will have to stage fewer blocks and therefore require fewer IO operations. The
* trade-offs between these values are context-dependent, so some experimentation may be required to optimize inputs
* for a given scenario.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.upload
* <pre>
* ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions&
* .setBlockSizeLong&
* .setMaxConcurrency&
* boolean overwrite = false; &
* client.upload&
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.upload
*
* @param data The data to write to the blob. Unlike other upload methods, this method does not require that the
* {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected
* to produce the same values across subscriptions.
* @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading.
* @param overwrite Whether to overwrite, should the blob already exist.
* @return A reactive response containing the information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlockBlobItem> upload(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions,
boolean overwrite) {
Mono<Void> overwriteCheck;
BlobRequestConditions requestConditions;
if (overwrite) {
overwriteCheck = Mono.empty();
requestConditions = null;
} else {
overwriteCheck = exists().flatMap(exists -> exists
? monoError(LOGGER, new IllegalArgumentException(Constants.BLOB_ALREADY_EXISTS))
: Mono.empty());
requestConditions = new BlobRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return overwriteCheck
.then(uploadWithResponse(data, parallelTransferOptions, null, null, null, requestConditions))
.flatMap(FluxUtil::toMono);
}
/**
* Creates a new block blob. By default, this method will not overwrite an existing blob.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.upload
* <pre>
* client.upload&
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.upload
*
* @param data The data to write to the blob.
* @return A reactive response containing the information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlockBlobItem> upload(BinaryData data) {
return upload(data, false);
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.upload
* <pre>
* boolean overwrite = false; &
* client.upload&
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.upload
*
* @param data The data to write to the blob.
* @param overwrite Whether to overwrite, should the blob already exist.
* @return A reactive response containing the information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlockBlobItem> upload(BinaryData data, boolean overwrite) {
Mono<Void> overwriteCheck;
BlobRequestConditions requestConditions;
if (overwrite) {
overwriteCheck = Mono.empty();
requestConditions = null;
} else {
overwriteCheck = exists().flatMap(exists -> exists
? monoError(LOGGER, new IllegalArgumentException(Constants.BLOB_ALREADY_EXISTS))
: Mono.empty());
requestConditions = new BlobRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return overwriteCheck
.then(uploadWithResponse(data.toFluxByteBuffer(), null, null, null, null, requestConditions))
.flatMap(FluxUtil::toMono);
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with this method; the content of the existing blob is overwritten with the new content. To perform a partial
* update of a block blob's, use {@link BlockBlobAsyncClient
* BlockBlobAsyncClient
* <a href="https:
* <a href="https:
* <p>
* The data passed need not support multiple subscriptions/be replayable as is required in other upload methods when
* retries are enabled, and the length of the data need not be known in advance. Therefore, this method does
* support uploading any arbitrary data source, including network streams. This behavior is possible because this
* method will perform some internal buffering as configured by the blockSize and numBuffers parameters, so while
* this method may offer additional convenience, it will not be as performant as other options, which should be
* preferred when possible.
* <p>
* Typically, the greater the number of buffers used, the greater the possible parallelism when transferring the
* data. Larger buffers means we will have to stage fewer blocks and therefore require fewer IO operations. The
* trade-offs between these values are context-dependent, so some experimentation may be required to optimize inputs
* for a given scenario.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.uploadWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
*
* ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions&
* .setBlockSizeLong&
* .setMaxConcurrency&
*
* client.uploadWithResponse&
* .subscribe&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.uploadWithResponse
*
* <p><strong>Using Progress Reporting</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.uploadWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
*
* ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions&
* .setBlockSizeLong&
* .setMaxConcurrency&
* .setProgressReceiver&
*
* client.uploadWithResponse&
* .subscribe&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.uploadWithResponse
*
* @param data The data to write to the blob. Unlike other upload methods, this method does not require that the
* {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected
* to produce the same values across subscriptions.
* @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading.
* @param headers {@link BlobHttpHeaders}
* @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param tier {@link AccessTier} for the destination blob.
* @param requestConditions {@link BlobRequestConditions}
* @return A reactive response containing the information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlockBlobItem>> uploadWithResponse(Flux<ByteBuffer> data,
ParallelTransferOptions parallelTransferOptions, BlobHttpHeaders headers, Map<String, String> metadata,
AccessTier tier, BlobRequestConditions requestConditions) {
try {
return this.uploadWithResponse(new BlobParallelUploadOptions(data)
.setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata)
.setTier(tier).setRequestConditions(requestConditions));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with this method; the content of the existing blob is overwritten with the new content. To perform a partial
* update of a block blob's, use {@link BlockBlobAsyncClient
* BlockBlobAsyncClient
* <a href="https:
* <a href="https:
* <p>
* The data passed need not support multiple subscriptions/be replayable as is required in other upload methods when
* retries are enabled, and the length of the data need not be known in advance. Therefore, this method does
* support uploading any arbitrary data source, including network streams. This behavior is possible because this
* method will perform some internal buffering as configured by the blockSize and numBuffers parameters, so while
* this method may offer additional convenience, it will not be as performant as other options, which should be
* preferred when possible.
* <p>
* Typically, the greater the number of buffers used, the greater the possible parallelism when transferring the
* data. Larger buffers means we will have to stage fewer blocks and therefore require fewer IO operations. The
* trade-offs between these values are context-dependent, so some experimentation may be required to optimize inputs
* for a given scenario.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.uploadWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
*
* ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions&
* .setMaxConcurrency&
* System.out.printf&
*
* client.uploadWithResponse&
* .setParallelTransferOptions&
* .setTier&
* .subscribe&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.uploadWithResponse
*
* <p><strong>Using Progress Reporting</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.uploadWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
*
* ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions&
* .setMaxConcurrency&
* System.out.printf&
*
* client.uploadWithResponse&
* .setParallelTransferOptions&
* .setTier&
* .subscribe&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.uploadWithResponse
*
* @param options {@link BlobParallelUploadOptions}. Unlike other upload methods, this method does not require that
* the {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not
* expected to produce the same values across subscriptions.
* @return A reactive response containing the information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlockBlobItem>> uploadWithResponse(BlobParallelUploadOptions options) {
/*
The following is catalogue of all the places we allocate memory/copy in any upload method a justification for
that case current as of 1/13/21.
- Async buffered upload chunked upload: We used an UploadBufferPool. This will allocate memory as needed up to
the configured maximum. This is necessary to support replayability on retires. Each flux to come out of the pool
is a Flux.just() of up to two deep copied buffers, so it is replayable. It also allows us to optimize the upload
by uploading the maximum amount per block. Finally, in the case of chunked uploading, it allows the customer to
pass data without knowing the size. Note that full upload does not need a deep copy because the Flux emitted by
the PayloadSizeGate in the full upload case is already replayable and the length is maintained by the gate.
- Sync buffered upload: converting the input stream to a flux involves creating a buffer for each stream read.
Using a new buffer per read ensures that the reads are safe and not overwriting data in buffers that were passed
to the async upload but have not yet been sent. This covers both full and chunked uploads in the sync case.
- BlobOutputStream: A deep copy is made of any buffer passed to write. While async copy does streamline our code
and allow for some potential parallelization, this extra copy is necessary to ensure that customers writing to
the stream in a tight loop are not overwriting data previously given to the stream before it has been sent.
Taken together, these should support retries and protect against data being overwritten in all upload scenarios.
One note is that there is no deep copy in the uploadFull method. This is unnecessary as explained in
uploadFullOrChunked because the Flux coming out of the size gate in that case is already replayable and reusing
buffers is not a common scenario for async like it is in sync (and we already buffer in sync to convert from a
stream).
*/
try {
StorageImplUtils.assertNotNull("options", options);
final ParallelTransferOptions parallelTransferOptions =
ModelHelper.populateAndApplyDefaults(options.getParallelTransferOptions());
final BlobHttpHeaders headers = options.getHeaders();
final Map<String, String> metadata = options.getMetadata();
final Map<String, String> tags = options.getTags();
final AccessTier tier = options.getTier();
final BlobRequestConditions requestConditions = options.getRequestConditions() == null
? new BlobRequestConditions() : options.getRequestConditions();
final boolean computeMd5 = options.isComputeMd5();
final BlobImmutabilityPolicy immutabilityPolicy = options.getImmutabilityPolicy() == null
? new BlobImmutabilityPolicy() : options.getImmutabilityPolicy();
final Boolean legalHold = options.isLegalHold();
BlockBlobAsyncClient blockBlobAsyncClient = getBlockBlobAsyncClient();
Function<Flux<ByteBuffer>, Mono<Response<BlockBlobItem>>> uploadInChunksFunction = (stream) ->
uploadInChunks(blockBlobAsyncClient, stream, parallelTransferOptions, headers, metadata, tags,
tier, requestConditions, computeMd5, immutabilityPolicy, legalHold);
BiFunction<Flux<ByteBuffer>, Long, Mono<Response<BlockBlobItem>>> uploadFullBlobFunction =
(stream, length) -> uploadFullBlob(blockBlobAsyncClient, stream, length, parallelTransferOptions,
headers, metadata, tags, tier, requestConditions, computeMd5, immutabilityPolicy, legalHold);
Flux<ByteBuffer> data = options.getDataFlux();
if (data == null && options.getOptionalLength() == null) {
int chunkSize = (int) Math.min(Constants.MAX_INPUT_STREAM_CONVERTER_BUFFER_LENGTH,
parallelTransferOptions.getBlockSizeLong());
data = FluxUtil.toFluxByteBuffer(options.getDataStream(), chunkSize);
} else if (data == null) {
int chunkSize = (int) Math.min(Constants.MAX_INPUT_STREAM_CONVERTER_BUFFER_LENGTH,
parallelTransferOptions.getBlockSizeLong());
data = Utility.convertStreamToByteBuffer(
options.getDataStream(), options.getOptionalLength(), chunkSize, false);
}
return UploadUtils.uploadFullOrChunked(data, ModelHelper.wrapBlobOptions(parallelTransferOptions),
uploadInChunksFunction, uploadFullBlobFunction);
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
private Mono<Response<BlockBlobItem>> uploadFullBlob(BlockBlobAsyncClient blockBlobAsyncClient,
Flux<ByteBuffer> data, long length, ParallelTransferOptions parallelTransferOptions, BlobHttpHeaders headers,
Map<String, String> metadata, Map<String, String> tags, AccessTier tier,
BlobRequestConditions requestConditions, boolean computeMd5, BlobImmutabilityPolicy immutabilityPolicy,
Boolean legalHold) {
/*
Note that there is no need to buffer here as the flux returned by the size gate in this case is created
from an iterable and is therefore replayable.
*/
Flux<ByteBuffer> progressData = ProgressReporter.addProgressReporting(data,
parallelTransferOptions.getProgressReceiver());
return UploadUtils.computeMd5(progressData, computeMd5, LOGGER)
.map(fluxMd5Wrapper -> new BlockBlobSimpleUploadOptions(fluxMd5Wrapper.getData(), length)
.setHeaders(headers)
.setMetadata(metadata)
.setTags(tags)
.setTier(tier)
.setRequestConditions(requestConditions)
.setContentMd5(fluxMd5Wrapper.getMd5())
.setImmutabilityPolicy(immutabilityPolicy)
.setLegalHold(legalHold))
.flatMap(blockBlobAsyncClient::uploadWithResponse);
}
private Mono<Response<BlockBlobItem>> uploadInChunks(BlockBlobAsyncClient blockBlobAsyncClient,
Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions, BlobHttpHeaders headers,
Map<String, String> metadata, Map<String, String> tags, AccessTier tier,
BlobRequestConditions requestConditions, boolean computeMd5, BlobImmutabilityPolicy immutabilityPolicy,
Boolean legalHold) {
AtomicLong totalProgress = new AtomicLong();
Lock progressLock = new ReentrantLock();
BufferStagingArea stagingArea = new BufferStagingArea(parallelTransferOptions.getBlockSizeLong(),
BlockBlobClient.MAX_STAGE_BLOCK_BYTES_LONG);
Flux<ByteBuffer> chunkedSource = UploadUtils.chunkSource(data,
ModelHelper.wrapBlobOptions(parallelTransferOptions));
/*
Write to the pool and upload the output.
maxConcurrency = 1 when writing means only 1 BufferAggregator will be accumulating at a time.
parallelTransferOptions.getMaxConcurrency() appends will be happening at once, so we guarantee buffering of
only concurrency + 1 chunks at a time.
*/
return chunkedSource.flatMapSequential(stagingArea::write, 1, 1)
.concatWith(Flux.defer(stagingArea::flush))
.flatMapSequential(bufferAggregator -> {
Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting(
bufferAggregator.asFlux(),
parallelTransferOptions.getProgressReceiver(),
progressLock,
totalProgress);
final String blockId = Base64.getEncoder().encodeToString(UUID.randomUUID().toString().getBytes(UTF_8));
return UploadUtils.computeMd5(progressData, computeMd5, LOGGER)
.flatMap(fluxMd5Wrapper -> blockBlobAsyncClient.stageBlockWithResponse(blockId,
fluxMd5Wrapper.getData(), bufferAggregator.length(), fluxMd5Wrapper.getMd5(),
requestConditions.getLeaseId()))
.map(x -> blockId)
.flux();
}, parallelTransferOptions.getMaxConcurrency(), 1)
.collect(Collectors.toList())
.flatMap(ids ->
blockBlobAsyncClient.commitBlockListWithResponse(new BlockBlobCommitBlockListOptions(ids)
.setHeaders(headers).setMetadata(metadata).setTags(tags).setTier(tier)
.setRequestConditions(requestConditions).setImmutabilityPolicy(immutabilityPolicy)
.setLegalHold(legalHold)));
}
/**
* Creates a new block blob with the content of the specified file. By default, this method will not overwrite an
* existing blob.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.uploadFromFile
* <pre>
* client.uploadFromFile&
* .doOnError&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.uploadFromFile
*
* @param filePath Path to the upload file
* @return An empty response
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> uploadFromFile(String filePath) {
return uploadFromFile(filePath, false);
}
/**
* Creates a new block blob, or updates the content of an existing block blob, with the content of the specified
* file.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.uploadFromFile
* <pre>
* boolean overwrite = false; &
* client.uploadFromFile&
* .doOnError&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.uploadFromFile
*
* @param filePath Path to the upload file
* @param overwrite Whether to overwrite, should the blob already exist.
* @return An empty response
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Creates a new block blob, or updates the content of an existing block blob, with the content of the specified
* file.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.uploadFromFile
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
*
* client.uploadFromFile&
* new ParallelTransferOptions&
* headers, metadata, AccessTier.HOT, requestConditions&
* .doOnError&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.uploadFromFile
*
* @param filePath Path to the upload file
* @param parallelTransferOptions {@link ParallelTransferOptions} to use to upload from file. Number of parallel
* transfers parameter is ignored.
* @param headers {@link BlobHttpHeaders}
* @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param tier {@link AccessTier} for the destination blob.
* @param requestConditions {@link BlobRequestConditions}
* @return An empty response
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> uploadFromFile(String filePath, ParallelTransferOptions parallelTransferOptions,
BlobHttpHeaders headers, Map<String, String> metadata, AccessTier tier,
BlobRequestConditions requestConditions) {
try {
return this.uploadFromFileWithResponse(new BlobUploadFromFileOptions(filePath)
.setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata)
.setTier(tier).setRequestConditions(requestConditions))
.then();
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Creates a new block blob, or updates the content of an existing block blob, with the content of the specified
* file.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.BlobAsyncClient.uploadFromFileWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
*
* client.uploadFromFileWithResponse&
* .setParallelTransferOptions&
* new ParallelTransferOptions&
* .setHeaders&
* .setRequestConditions&
* .doOnError&
* .subscribe&
* </pre>
* <!-- end com.azure.storage.blob.BlobAsyncClient.uploadFromFileWithResponse
*
* @param options {@link BlobUploadFromFileOptions}
* @return A reactive response containing the information of the uploaded block blob.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlockBlobItem>> uploadFromFileWithResponse(BlobUploadFromFileOptions options) {
StorageImplUtils.assertNotNull("options", options);
Long originalBlockSize = (options.getParallelTransferOptions() == null)
? null
: options.getParallelTransferOptions().getBlockSizeLong();
final ParallelTransferOptions finalParallelTransferOptions =
ModelHelper.populateAndApplyDefaults(options.getParallelTransferOptions());
try {
return Mono.using(() -> UploadUtils.uploadFileResourceSupplier(options.getFilePath(), LOGGER),
channel -> {
try {
BlockBlobAsyncClient blockBlobAsyncClient = getBlockBlobAsyncClient();
long fileSize = channel.size();
if (UploadUtils.shouldUploadInChunks(options.getFilePath(),
finalParallelTransferOptions.getMaxSingleUploadSizeLong(), LOGGER)) {
return uploadFileChunks(fileSize, finalParallelTransferOptions, originalBlockSize,
options.getHeaders(), options.getMetadata(), options.getTags(),
options.getTier(), options.getRequestConditions(), channel,
blockBlobAsyncClient);
} else {
Flux<ByteBuffer> data = FluxUtil.readFile(channel);
if (finalParallelTransferOptions.getProgressReceiver() != null) {
data = ProgressReporter.addProgressReporting(data,
finalParallelTransferOptions.getProgressReceiver());
}
return blockBlobAsyncClient.uploadWithResponse(
new BlockBlobSimpleUploadOptions(data, fileSize).setHeaders(options.getHeaders())
.setMetadata(options.getMetadata()).setTags(options.getTags())
.setTier(options.getTier())
.setRequestConditions(options.getRequestConditions()));
}
} catch (IOException ex) {
return Mono.error(ex);
}
},
channel ->
UploadUtils.uploadFileCleanup(channel, LOGGER));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
private Mono<Response<BlockBlobItem>> uploadFileChunks(
long fileSize, ParallelTransferOptions parallelTransferOptions,
Long originalBlockSize, BlobHttpHeaders headers, Map<String, String> metadata, Map<String, String> tags,
AccessTier tier, BlobRequestConditions requestConditions, AsynchronousFileChannel channel,
BlockBlobAsyncClient client) {
final BlobRequestConditions finalRequestConditions = (requestConditions == null)
? new BlobRequestConditions() : requestConditions;
AtomicLong totalProgress = new AtomicLong();
Lock progressLock = new ReentrantLock();
final SortedMap<Long, String> blockIds = new TreeMap<>();
return Flux.fromIterable(sliceFile(fileSize, originalBlockSize, parallelTransferOptions.getBlockSizeLong()))
.flatMap(chunk -> {
String blockId = getBlockID();
blockIds.put(chunk.getOffset(), blockId);
Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting(
FluxUtil.readFile(channel, chunk.getOffset(), chunk.getCount()),
parallelTransferOptions.getProgressReceiver(), progressLock, totalProgress);
return client.stageBlockWithResponse(blockId, progressData, chunk.getCount(), null,
finalRequestConditions.getLeaseId());
}, parallelTransferOptions.getMaxConcurrency())
.then(Mono.defer(() -> client.commitBlockListWithResponse(
new BlockBlobCommitBlockListOptions(new ArrayList<>(blockIds.values()))
.setHeaders(headers).setMetadata(metadata).setTags(tags).setTier(tier)
.setRequestConditions(finalRequestConditions))));
}
/**
* RESERVED FOR INTERNAL USE.
*
* Resource Supplier for UploadFile.
*
* @param filePath The path for the file
* @return {@code AsynchronousFileChannel}
* @throws UncheckedIOException an input output exception.
* @deprecated due to refactoring code to be in the common storage library.
*/
@Deprecated
protected AsynchronousFileChannel uploadFileResourceSupplier(String filePath) {
return UploadUtils.uploadFileResourceSupplier(filePath, LOGGER);
}
private String getBlockID() {
return Base64.getEncoder().encodeToString(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));
}
private List<BlobRange> sliceFile(long fileSize, Long originalBlockSize, long blockSize) {
List<BlobRange> ranges = new ArrayList<>();
if (fileSize > 100 * Constants.MB && originalBlockSize == null) {
blockSize = BLOB_DEFAULT_HTBB_UPLOAD_BLOCK_SIZE;
}
for (long pos = 0; pos < fileSize; pos += blockSize) {
long count = blockSize;
if (pos + count > fileSize) {
count = fileSize - pos;
}
ranges.add(new BlobRange(pos, count));
}
return ranges;
}
} |
can this even happen? | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
return Mono.defer(() -> {
OffsetDateTime now = OffsetDateTime.now();
try {
context.getHttpRequest().getHeaders().set("Date", DateTimeRfc1123.toRfc1123String(now));
} catch (IllegalArgumentException ignored) {
context.getHttpRequest().getHeaders().set("Date", FORMATTER.format(now));
}
return next.process();
});
} | } | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
return Mono.defer(() -> {
OffsetDateTime now = OffsetDateTime.now();
try {
context.getHttpRequest().getHeaders().set("Date", DateTimeRfc1123.toRfc1123String(now));
} catch (IllegalArgumentException ignored) {
context.getHttpRequest().getHeaders().set("Date", FORMATTER.format(now));
}
return next.process();
});
} | class AddDatePolicy implements HttpPipelinePolicy {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter
.ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'")
.withZone(ZoneOffset.UTC)
.withLocale(Locale.US);
@Override
} | class AddDatePolicy implements HttpPipelinePolicy {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter
.ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'")
.withZone(ZoneOffset.UTC)
.withLocale(Locale.US);
@Override
} |
Would it be better to wrap in UncheckedIOException ? | public Mono<Void> logRequest(ClientLogger logger, HttpRequestLoggingContext loggingOptions) {
final LogLevel logLevel = getLogLevel(loggingOptions);
if (!logger.canLogAtLevel(logLevel)) {
return Mono.empty();
}
final HttpRequest request = loggingOptions.getHttpRequest();
StringBuilder requestLogMessage = new StringBuilder();
if (httpLogDetailLevel.shouldLogUrl()) {
requestLogMessage.append("--> ")
.append(request.getHttpMethod())
.append(" ")
.append(getRedactedUrl(request.getUrl(), allowedQueryParameterNames))
.append(System.lineSeparator());
Integer retryCount = loggingOptions.getTryCount();
if (retryCount != null) {
requestLogMessage.append("Try count: ")
.append(retryCount)
.append(System.lineSeparator());
}
}
if (httpLogDetailLevel.shouldLogHeaders() && logger.canLogAtLevel(LogLevel.VERBOSE)) {
addHeadersToLogMessage(allowedHeaderNames, request.getHeaders(), requestLogMessage);
}
if (!httpLogDetailLevel.shouldLogBody()) {
return logAndReturn(logger, logLevel, requestLogMessage, null);
}
if (request.getBody() == null) {
requestLogMessage.append("(empty body)")
.append(System.lineSeparator())
.append("--> END ")
.append(request.getHttpMethod())
.append(System.lineSeparator());
return logAndReturn(logger, logLevel, requestLogMessage, null);
}
String contentType = request.getHeaders().getValue("Content-Type");
long contentLength = getContentLength(logger, request.getHeaders());
if (shouldBodyBeLogged(contentType, contentLength)) {
AccessibleByteArrayOutputStream stream = new AccessibleByteArrayOutputStream((int) contentLength);
request.setBody(
request.getBody()
.doOnNext(byteBuffer -> {
try {
ImplUtils.writeByteBufferToStream(byteBuffer.duplicate(), stream);
} catch (IOException ex) {
throw LOGGER.logExceptionAsError(Exceptions.propagate(ex));
}
})
.doFinally(ignored -> {
requestLogMessage.append(contentLength)
.append("-byte body:")
.append(System.lineSeparator())
.append(prettyPrintIfNeeded(logger, prettyPrintBody, contentType,
new String(stream.toByteArray(), 0, stream.count(), StandardCharsets.UTF_8)))
.append(System.lineSeparator())
.append("--> END ")
.append(request.getHttpMethod())
.append(System.lineSeparator());
logAndReturn(logger, logLevel, requestLogMessage, null);
}));
return Mono.empty();
} else {
requestLogMessage.append(contentLength)
.append("-byte body: (content not logged)")
.append(System.lineSeparator())
.append("--> END ")
.append(request.getHttpMethod())
.append(System.lineSeparator());
return logAndReturn(logger, logLevel, requestLogMessage, null);
}
} | throw LOGGER.logExceptionAsError(Exceptions.propagate(ex)); | public Mono<Void> logRequest(ClientLogger logger, HttpRequestLoggingContext loggingOptions) {
final LogLevel logLevel = getLogLevel(loggingOptions);
if (!logger.canLogAtLevel(logLevel)) {
return Mono.empty();
}
final HttpRequest request = loggingOptions.getHttpRequest();
StringBuilder requestLogMessage = new StringBuilder();
if (httpLogDetailLevel.shouldLogUrl()) {
requestLogMessage.append("--> ")
.append(request.getHttpMethod())
.append(" ")
.append(getRedactedUrl(request.getUrl(), allowedQueryParameterNames))
.append(System.lineSeparator());
Integer retryCount = loggingOptions.getTryCount();
if (retryCount != null) {
requestLogMessage.append("Try count: ")
.append(retryCount)
.append(System.lineSeparator());
}
}
if (httpLogDetailLevel.shouldLogHeaders() && logger.canLogAtLevel(LogLevel.VERBOSE)) {
addHeadersToLogMessage(allowedHeaderNames, request.getHeaders(), requestLogMessage);
}
if (!httpLogDetailLevel.shouldLogBody()) {
logMessage(logger, logLevel, requestLogMessage);
return Mono.empty();
}
if (request.getBody() == null) {
requestLogMessage.append("(empty body)")
.append(System.lineSeparator())
.append("--> END ")
.append(request.getHttpMethod())
.append(System.lineSeparator());
logMessage(logger, logLevel, requestLogMessage);
return Mono.empty();
}
String contentType = request.getHeaders().getValue("Content-Type");
long contentLength = getContentLength(logger, request.getHeaders());
if (shouldBodyBeLogged(contentType, contentLength)) {
AccessibleByteArrayOutputStream stream = new AccessibleByteArrayOutputStream((int) contentLength);
request.setBody(
request.getBody()
.doOnNext(byteBuffer -> {
try {
ImplUtils.writeByteBufferToStream(byteBuffer.duplicate(), stream);
} catch (IOException ex) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(ex));
}
})
.doFinally(ignored -> {
requestLogMessage.append(contentLength)
.append("-byte body:")
.append(System.lineSeparator())
.append(prettyPrintIfNeeded(logger, prettyPrintBody, contentType,
new String(stream.toByteArray(), 0, stream.count(), StandardCharsets.UTF_8)))
.append(System.lineSeparator())
.append("--> END ")
.append(request.getHttpMethod())
.append(System.lineSeparator());
logMessage(logger, logLevel, requestLogMessage);
}));
} else {
requestLogMessage.append(contentLength)
.append("-byte body: (content not logged)")
.append(System.lineSeparator())
.append("--> END ")
.append(request.getHttpMethod())
.append(System.lineSeparator());
logMessage(logger, logLevel, requestLogMessage);
}
return Mono.empty();
} | class DefaultHttpRequestLogger implements HttpRequestLogger {
@Override
} | class DefaultHttpRequestLogger implements HttpRequestLogger {
@Override
} |
these could be static singletons if we want to be even faster. | private static HttpPipeline createDefaultPipeline() {
return new HttpPipelineBuilder()
.policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy())
.build();
} | .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()) | private static HttpPipeline createDefaultPipeline() {
return new HttpPipelineBuilder()
.policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy())
.build();
} | class " + cls))))
.flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject));
}
private Mono<?> handleBodyReturnType(final HttpDecodedResponse response,
final SwaggerMethodParser methodParser, final Type entityType) {
final int responseStatusCode = response.getSourceResponse().getStatusCode();
final HttpMethod httpMethod = methodParser.getHttpMethod();
final Type returnValueWireType = methodParser.getReturnValueWireType();
final Mono<?> asyncResult;
if (httpMethod == HttpMethod.HEAD
&& (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE)
|| TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) {
boolean isSuccess = (responseStatusCode / 100) == 2;
asyncResult = Mono.just(isSuccess);
} else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) {
Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray();
if (returnValueWireType == Base64Url.class) {
responseBodyBytesAsync = responseBodyBytesAsync
.mapNotNull(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes());
}
asyncResult = responseBodyBytesAsync;
} else if (FluxUtil.isFluxByteBuffer(entityType)) {
asyncResult = Mono.just(response.getSourceResponse().getBody());
} else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) {
asyncResult = BinaryData.fromFlux(response.getSourceResponse().getBody());
} else {
asyncResult = response.getDecodedBody((byte[]) null);
}
return asyncResult;
} | class " + cls))))
.flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject));
}
private Mono<?> handleBodyReturnType(final HttpDecodedResponse response,
final SwaggerMethodParser methodParser, final Type entityType) {
final int responseStatusCode = response.getSourceResponse().getStatusCode();
final HttpMethod httpMethod = methodParser.getHttpMethod();
final Type returnValueWireType = methodParser.getReturnValueWireType();
final Mono<?> asyncResult;
if (httpMethod == HttpMethod.HEAD
&& (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE)
|| TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) {
boolean isSuccess = (responseStatusCode / 100) == 2;
asyncResult = Mono.just(isSuccess);
} else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) {
Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray();
if (returnValueWireType == Base64Url.class) {
responseBodyBytesAsync = responseBodyBytesAsync
.mapNotNull(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes());
}
asyncResult = responseBodyBytesAsync;
} else if (FluxUtil.isFluxByteBuffer(entityType)) {
asyncResult = Mono.just(response.getSourceResponse().getBody());
} else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) {
asyncResult = BinaryData.fromFlux(response.getSourceResponse().getBody());
} else {
asyncResult = response.getDecodedBody((byte[]) null);
}
return asyncResult;
} |
Likely not, but I'd rather have this in for the time being as if this fails the request will likely fail as well. We can add a log message here and if it doesn't come up during long-running testing this can be removed. | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
return Mono.defer(() -> {
OffsetDateTime now = OffsetDateTime.now();
try {
context.getHttpRequest().getHeaders().set("Date", DateTimeRfc1123.toRfc1123String(now));
} catch (IllegalArgumentException ignored) {
context.getHttpRequest().getHeaders().set("Date", FORMATTER.format(now));
}
return next.process();
});
} | } | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
return Mono.defer(() -> {
OffsetDateTime now = OffsetDateTime.now();
try {
context.getHttpRequest().getHeaders().set("Date", DateTimeRfc1123.toRfc1123String(now));
} catch (IllegalArgumentException ignored) {
context.getHttpRequest().getHeaders().set("Date", FORMATTER.format(now));
}
return next.process();
});
} | class AddDatePolicy implements HttpPipelinePolicy {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter
.ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'")
.withZone(ZoneOffset.UTC)
.withLocale(Locale.US);
@Override
} | class AddDatePolicy implements HttpPipelinePolicy {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter
.ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'")
.withZone(ZoneOffset.UTC)
.withLocale(Locale.US);
@Override
} |
Good idea, don't know if this is ever called, but we need to keep it since it's public API (unfortunately). | private static HttpPipeline createDefaultPipeline() {
return new HttpPipelineBuilder()
.policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy())
.build();
} | .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()) | private static HttpPipeline createDefaultPipeline() {
return new HttpPipelineBuilder()
.policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy())
.build();
} | class " + cls))))
.flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject));
}
private Mono<?> handleBodyReturnType(final HttpDecodedResponse response,
final SwaggerMethodParser methodParser, final Type entityType) {
final int responseStatusCode = response.getSourceResponse().getStatusCode();
final HttpMethod httpMethod = methodParser.getHttpMethod();
final Type returnValueWireType = methodParser.getReturnValueWireType();
final Mono<?> asyncResult;
if (httpMethod == HttpMethod.HEAD
&& (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE)
|| TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) {
boolean isSuccess = (responseStatusCode / 100) == 2;
asyncResult = Mono.just(isSuccess);
} else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) {
Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray();
if (returnValueWireType == Base64Url.class) {
responseBodyBytesAsync = responseBodyBytesAsync
.mapNotNull(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes());
}
asyncResult = responseBodyBytesAsync;
} else if (FluxUtil.isFluxByteBuffer(entityType)) {
asyncResult = Mono.just(response.getSourceResponse().getBody());
} else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) {
asyncResult = BinaryData.fromFlux(response.getSourceResponse().getBody());
} else {
asyncResult = response.getDecodedBody((byte[]) null);
}
return asyncResult;
} | class " + cls))))
.flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject));
}
private Mono<?> handleBodyReturnType(final HttpDecodedResponse response,
final SwaggerMethodParser methodParser, final Type entityType) {
final int responseStatusCode = response.getSourceResponse().getStatusCode();
final HttpMethod httpMethod = methodParser.getHttpMethod();
final Type returnValueWireType = methodParser.getReturnValueWireType();
final Mono<?> asyncResult;
if (httpMethod == HttpMethod.HEAD
&& (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE)
|| TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) {
boolean isSuccess = (responseStatusCode / 100) == 2;
asyncResult = Mono.just(isSuccess);
} else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) {
Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray();
if (returnValueWireType == Base64Url.class) {
responseBodyBytesAsync = responseBodyBytesAsync
.mapNotNull(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes());
}
asyncResult = responseBodyBytesAsync;
} else if (FluxUtil.isFluxByteBuffer(entityType)) {
asyncResult = Mono.just(response.getSourceResponse().getBody());
} else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) {
asyncResult = BinaryData.fromFlux(response.getSourceResponse().getBody());
} else {
asyncResult = response.getDecodedBody((byte[]) null);
}
return asyncResult;
} |
Done | public Mono<Void> logRequest(ClientLogger logger, HttpRequestLoggingContext loggingOptions) {
final LogLevel logLevel = getLogLevel(loggingOptions);
if (!logger.canLogAtLevel(logLevel)) {
return Mono.empty();
}
final HttpRequest request = loggingOptions.getHttpRequest();
StringBuilder requestLogMessage = new StringBuilder();
if (httpLogDetailLevel.shouldLogUrl()) {
requestLogMessage.append("--> ")
.append(request.getHttpMethod())
.append(" ")
.append(getRedactedUrl(request.getUrl(), allowedQueryParameterNames))
.append(System.lineSeparator());
Integer retryCount = loggingOptions.getTryCount();
if (retryCount != null) {
requestLogMessage.append("Try count: ")
.append(retryCount)
.append(System.lineSeparator());
}
}
if (httpLogDetailLevel.shouldLogHeaders() && logger.canLogAtLevel(LogLevel.VERBOSE)) {
addHeadersToLogMessage(allowedHeaderNames, request.getHeaders(), requestLogMessage);
}
if (!httpLogDetailLevel.shouldLogBody()) {
return logAndReturn(logger, logLevel, requestLogMessage, null);
}
if (request.getBody() == null) {
requestLogMessage.append("(empty body)")
.append(System.lineSeparator())
.append("--> END ")
.append(request.getHttpMethod())
.append(System.lineSeparator());
return logAndReturn(logger, logLevel, requestLogMessage, null);
}
String contentType = request.getHeaders().getValue("Content-Type");
long contentLength = getContentLength(logger, request.getHeaders());
if (shouldBodyBeLogged(contentType, contentLength)) {
AccessibleByteArrayOutputStream stream = new AccessibleByteArrayOutputStream((int) contentLength);
request.setBody(
request.getBody()
.doOnNext(byteBuffer -> {
try {
ImplUtils.writeByteBufferToStream(byteBuffer.duplicate(), stream);
} catch (IOException ex) {
throw LOGGER.logExceptionAsError(Exceptions.propagate(ex));
}
})
.doFinally(ignored -> {
requestLogMessage.append(contentLength)
.append("-byte body:")
.append(System.lineSeparator())
.append(prettyPrintIfNeeded(logger, prettyPrintBody, contentType,
new String(stream.toByteArray(), 0, stream.count(), StandardCharsets.UTF_8)))
.append(System.lineSeparator())
.append("--> END ")
.append(request.getHttpMethod())
.append(System.lineSeparator());
logAndReturn(logger, logLevel, requestLogMessage, null);
}));
return Mono.empty();
} else {
requestLogMessage.append(contentLength)
.append("-byte body: (content not logged)")
.append(System.lineSeparator())
.append("--> END ")
.append(request.getHttpMethod())
.append(System.lineSeparator());
return logAndReturn(logger, logLevel, requestLogMessage, null);
}
} | throw LOGGER.logExceptionAsError(Exceptions.propagate(ex)); | public Mono<Void> logRequest(ClientLogger logger, HttpRequestLoggingContext loggingOptions) {
final LogLevel logLevel = getLogLevel(loggingOptions);
if (!logger.canLogAtLevel(logLevel)) {
return Mono.empty();
}
final HttpRequest request = loggingOptions.getHttpRequest();
StringBuilder requestLogMessage = new StringBuilder();
if (httpLogDetailLevel.shouldLogUrl()) {
requestLogMessage.append("--> ")
.append(request.getHttpMethod())
.append(" ")
.append(getRedactedUrl(request.getUrl(), allowedQueryParameterNames))
.append(System.lineSeparator());
Integer retryCount = loggingOptions.getTryCount();
if (retryCount != null) {
requestLogMessage.append("Try count: ")
.append(retryCount)
.append(System.lineSeparator());
}
}
if (httpLogDetailLevel.shouldLogHeaders() && logger.canLogAtLevel(LogLevel.VERBOSE)) {
addHeadersToLogMessage(allowedHeaderNames, request.getHeaders(), requestLogMessage);
}
if (!httpLogDetailLevel.shouldLogBody()) {
logMessage(logger, logLevel, requestLogMessage);
return Mono.empty();
}
if (request.getBody() == null) {
requestLogMessage.append("(empty body)")
.append(System.lineSeparator())
.append("--> END ")
.append(request.getHttpMethod())
.append(System.lineSeparator());
logMessage(logger, logLevel, requestLogMessage);
return Mono.empty();
}
String contentType = request.getHeaders().getValue("Content-Type");
long contentLength = getContentLength(logger, request.getHeaders());
if (shouldBodyBeLogged(contentType, contentLength)) {
AccessibleByteArrayOutputStream stream = new AccessibleByteArrayOutputStream((int) contentLength);
request.setBody(
request.getBody()
.doOnNext(byteBuffer -> {
try {
ImplUtils.writeByteBufferToStream(byteBuffer.duplicate(), stream);
} catch (IOException ex) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(ex));
}
})
.doFinally(ignored -> {
requestLogMessage.append(contentLength)
.append("-byte body:")
.append(System.lineSeparator())
.append(prettyPrintIfNeeded(logger, prettyPrintBody, contentType,
new String(stream.toByteArray(), 0, stream.count(), StandardCharsets.UTF_8)))
.append(System.lineSeparator())
.append("--> END ")
.append(request.getHttpMethod())
.append(System.lineSeparator());
logMessage(logger, logLevel, requestLogMessage);
}));
} else {
requestLogMessage.append(contentLength)
.append("-byte body: (content not logged)")
.append(System.lineSeparator())
.append("--> END ")
.append(request.getHttpMethod())
.append(System.lineSeparator());
logMessage(logger, logLevel, requestLogMessage);
}
return Mono.empty();
} | class DefaultHttpRequestLogger implements HttpRequestLogger {
@Override
} | class DefaultHttpRequestLogger implements HttpRequestLogger {
@Override
} |
why do we design the interface to accept an argument of `abstract type` while in the implementation use its implementation? How about always using the implementation for clarity? By this way, we avoid the `is instanceof ` judgement then. | private EventHubsTemplate getEventHubTemplate() {
if (this.eventHubsTemplate == null) {
DefaultEventHubsNamespaceProducerFactory factory = new DefaultEventHubsNamespaceProducerFactory(
this.namespaceProperties, getProducerPropertiesSupplier());
producerFactoryCustomizers.forEach(customizer -> customizer.customize(factory));
factory.addListener((name, producerAsyncClient) -> {
DefaultInstrumentation instrumentation = new DefaultInstrumentation(name, PRODUCER);
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
this.eventHubsTemplate = new EventHubsTemplate(factory);
}
return this.eventHubsTemplate;
} | producerFactoryCustomizers.forEach(customizer -> customizer.customize(factory)); | private EventHubsTemplate getEventHubTemplate() {
if (this.eventHubsTemplate == null) {
DefaultEventHubsNamespaceProducerFactory factory = new DefaultEventHubsNamespaceProducerFactory(
this.namespaceProperties, getProducerPropertiesSupplier());
producerFactoryCustomizers.forEach(customizer -> customizer.customize(factory));
factory.addListener((name, producerAsyncClient) -> {
DefaultInstrumentation instrumentation = new DefaultInstrumentation(name, PRODUCER);
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
this.eventHubsTemplate = new EventHubsTemplate(factory);
}
return this.eventHubsTemplate;
} | class EventHubsMessageChannelBinder extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<EventHubsConsumerProperties>, ExtendedProducerProperties<EventHubsProducerProperties>, EventHubsChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, EventHubsConsumerProperties, EventHubsProducerProperties> {
private static final Logger LOGGER = LoggerFactory.getLogger(EventHubsMessageChannelBinder.class);
private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
private NamespaceProperties namespaceProperties;
private EventHubsTemplate eventHubsTemplate;
private CheckpointStore checkpointStore;
private DefaultEventHubsNamespaceProcessorFactory processorFactory;
private final List<EventHubsMessageListenerContainer> eventHubsMessageListenerContainers = new ArrayList<>();
private final InstrumentationManager instrumentationManager = new DefaultInstrumentationManager();
private EventHubsExtendedBindingProperties bindingProperties = new EventHubsExtendedBindingProperties();
private final Map<String, ExtendedProducerProperties<EventHubsProducerProperties>>
extendedProducerPropertiesMap = new ConcurrentHashMap<>();
private List<EventHubsProducerFactoryCustomizer> producerFactoryCustomizers = new ArrayList<>();
private List<EventHubsProcessorFactoryCustomizer> processorFactoryCustomizers = new ArrayList<>();
/**
* Construct a {@link EventHubsMessageChannelBinder} with the specified headers to embed and {@link EventHubsChannelProvisioner}.
*
* @param headersToEmbed the headers to embed
* @param provisioningProvider the provisioning provider
*/
public EventHubsMessageChannelBinder(String[] headersToEmbed, EventHubsChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(
ProducerDestination destination,
ExtendedProducerProperties<EventHubsProducerProperties> producerProperties,
MessageChannel errorChannel) {
extendedProducerPropertiesMap.put(destination.getName(), producerProperties);
Assert.notNull(getEventHubTemplate(), "eventHubsTemplate can't be null when create a producer");
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), this.eventHubsTemplate);
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout().toMillis());
handler.setSendFailureChannel(errorChannel);
String instrumentationId = Instrumentation.buildId(PRODUCER, destination.getName());
handler.setSendCallback(new InstrumentationSendCallback(instrumentationId, instrumentationManager));
if (producerProperties.isPartitioned()) {
handler.setPartitionIdExpression(
EXPRESSION_PARSER.parseExpression("headers['" + BinderHeaders.PARTITION_HEADER + "']"));
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
Assert.notNull(getProcessorFactory(), "processor factory can't be null when create a consumer");
boolean anonymous = !StringUtils.hasText(group);
if (anonymous) {
group = "anonymous." + UUID.randomUUID();
}
EventHubsContainerProperties containerProperties = createContainerProperties(destination, group, properties);
EventHubsMessageListenerContainer listenerContainer = new EventHubsMessageListenerContainer(
getProcessorFactory(), containerProperties);
this.eventHubsMessageListenerContainers.add(listenerContainer);
EventHubsInboundChannelAdapter inboundAdapter;
if (properties.isBatchMode()) {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer, ListenerMode.BATCH);
} else {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer);
}
inboundAdapter.setBeanFactory(getBeanFactory());
String instrumentationId = Instrumentation.buildId(CONSUMER, destination.getName() + "/" + group);
inboundAdapter.setInstrumentationManager(instrumentationManager);
inboundAdapter.setInstrumentationId(instrumentationId);
ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties);
inboundAdapter.setErrorChannel(errorInfrastructure.getErrorChannel());
return inboundAdapter;
}
/**
* Create {@link EventHubsContainerProperties} from the extended {@link EventHubsConsumerProperties}.
* @param destination reference to the consumer destination.
* @param group the consumer group.
* @param properties the consumer properties.
* @return the {@link EventHubsContainerProperties}.
*/
private EventHubsContainerProperties createContainerProperties(
ConsumerDestination destination,
String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
EventHubsContainerProperties containerProperties = new EventHubsContainerProperties();
AzurePropertiesUtils.copyAzureCommonProperties(properties.getExtension(), containerProperties);
ProcessorPropertiesMerger.copyProcessorPropertiesIfNotNull(properties.getExtension(), containerProperties);
containerProperties.setEventHubName(destination.getName());
containerProperties.setConsumerGroup(group);
containerProperties.setCheckpointConfig(properties.getExtension().getCheckpoint());
return containerProperties;
}
@Override
public EventHubsConsumerProperties getExtendedConsumerProperties(String destination) {
return this.bindingProperties.getExtendedConsumerProperties(destination);
}
@Override
public EventHubsProducerProperties getExtendedProducerProperties(String destination) {
return this.bindingProperties.getExtendedProducerProperties(destination);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
/**
* Set binding properties.
*
* @param bindingProperties the binding properties
*/
public void setBindingProperties(EventHubsExtendedBindingProperties bindingProperties) {
this.bindingProperties = bindingProperties;
}
private PropertiesSupplier<String, ProducerProperties> getProducerPropertiesSupplier() {
return key -> {
if (this.extendedProducerPropertiesMap.containsKey(key)) {
EventHubsProducerProperties producerProperties = this.extendedProducerPropertiesMap.get(key)
.getExtension();
producerProperties.setEventHubName(key);
return producerProperties;
} else {
LOGGER.debug("Can't find extended properties for {}", key);
return null;
}
};
}
private EventHubsProcessorFactory getProcessorFactory() {
if (this.processorFactory == null) {
this.processorFactory = new DefaultEventHubsNamespaceProcessorFactory(
this.checkpointStore, this.namespaceProperties);
processorFactoryCustomizers.forEach(customizer -> customizer.customize(processorFactory));
processorFactory.addListener((name, consumerGroup, processorClient) -> {
String instrumentationName = name + "/" + consumerGroup;
Instrumentation instrumentation = new EventHubsProcessorInstrumentation(instrumentationName, CONSUMER, Duration.ofMinutes(2));
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
}
return this.processorFactory;
}
/**
* Set namespace properties.
*
* @param namespaceProperties the namespace properties
*/
public void setNamespaceProperties(NamespaceProperties namespaceProperties) {
this.namespaceProperties = namespaceProperties;
}
/**
* Set checkpoint store.
*
* @param checkpointStore the checkpoint store
*/
public void setCheckpointStore(CheckpointStore checkpointStore) {
this.checkpointStore = checkpointStore;
}
/**
* Get instrumentation manager.
*
* @return instrumentationManager the instrumentation manager
* @see InstrumentationManager
*/
InstrumentationManager getInstrumentationManager() {
return instrumentationManager;
}
/**
* Set the producer factory customizers.
*
* @param producerFactoryCustomizers The producer factory customizers.
*/
public void setProducerFactoryCustomizers(List<EventHubsProducerFactoryCustomizer> producerFactoryCustomizers) {
this.producerFactoryCustomizers = producerFactoryCustomizers;
}
/**
* Set the processor factory customizers.
*
* @param processorFactoryCustomizers The processor factory customizers.
*/
public void setProcessorFactoryCustomizers(List<EventHubsProcessorFactoryCustomizer> processorFactoryCustomizers) {
this.processorFactoryCustomizers = processorFactoryCustomizers;
}
} | class EventHubsMessageChannelBinder extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<EventHubsConsumerProperties>, ExtendedProducerProperties<EventHubsProducerProperties>, EventHubsChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, EventHubsConsumerProperties, EventHubsProducerProperties> {
private static final Logger LOGGER = LoggerFactory.getLogger(EventHubsMessageChannelBinder.class);
private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
private NamespaceProperties namespaceProperties;
private EventHubsTemplate eventHubsTemplate;
private CheckpointStore checkpointStore;
private DefaultEventHubsNamespaceProcessorFactory processorFactory;
private final List<EventHubsMessageListenerContainer> eventHubsMessageListenerContainers = new ArrayList<>();
private final InstrumentationManager instrumentationManager = new DefaultInstrumentationManager();
private EventHubsExtendedBindingProperties bindingProperties = new EventHubsExtendedBindingProperties();
private final Map<String, ExtendedProducerProperties<EventHubsProducerProperties>>
extendedProducerPropertiesMap = new ConcurrentHashMap<>();
private List<EventHubsProducerFactoryCustomizer> producerFactoryCustomizers = new ArrayList<>();
private List<EventHubsProcessorFactoryCustomizer> processorFactoryCustomizers = new ArrayList<>();
/**
* Construct a {@link EventHubsMessageChannelBinder} with the specified headers to embed and {@link EventHubsChannelProvisioner}.
*
* @param headersToEmbed the headers to embed
* @param provisioningProvider the provisioning provider
*/
public EventHubsMessageChannelBinder(String[] headersToEmbed, EventHubsChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(
ProducerDestination destination,
ExtendedProducerProperties<EventHubsProducerProperties> producerProperties,
MessageChannel errorChannel) {
extendedProducerPropertiesMap.put(destination.getName(), producerProperties);
Assert.notNull(getEventHubTemplate(), "eventHubsTemplate can't be null when create a producer");
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), this.eventHubsTemplate);
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout().toMillis());
handler.setSendFailureChannel(errorChannel);
String instrumentationId = Instrumentation.buildId(PRODUCER, destination.getName());
handler.setSendCallback(new InstrumentationSendCallback(instrumentationId, instrumentationManager));
if (producerProperties.isPartitioned()) {
handler.setPartitionIdExpression(
EXPRESSION_PARSER.parseExpression("headers['" + BinderHeaders.PARTITION_HEADER + "']"));
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
Assert.notNull(getProcessorFactory(), "processor factory can't be null when create a consumer");
boolean anonymous = !StringUtils.hasText(group);
if (anonymous) {
group = "anonymous." + UUID.randomUUID();
}
EventHubsContainerProperties containerProperties = createContainerProperties(destination, group, properties);
EventHubsMessageListenerContainer listenerContainer = new EventHubsMessageListenerContainer(
getProcessorFactory(), containerProperties);
this.eventHubsMessageListenerContainers.add(listenerContainer);
EventHubsInboundChannelAdapter inboundAdapter;
if (properties.isBatchMode()) {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer, ListenerMode.BATCH);
} else {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer);
}
inboundAdapter.setBeanFactory(getBeanFactory());
String instrumentationId = Instrumentation.buildId(CONSUMER, destination.getName() + "/" + group);
inboundAdapter.setInstrumentationManager(instrumentationManager);
inboundAdapter.setInstrumentationId(instrumentationId);
ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties);
inboundAdapter.setErrorChannel(errorInfrastructure.getErrorChannel());
return inboundAdapter;
}
/**
* Create {@link EventHubsContainerProperties} from the extended {@link EventHubsConsumerProperties}.
* @param destination reference to the consumer destination.
* @param group the consumer group.
* @param properties the consumer properties.
* @return the {@link EventHubsContainerProperties}.
*/
private EventHubsContainerProperties createContainerProperties(
ConsumerDestination destination,
String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
EventHubsContainerProperties containerProperties = new EventHubsContainerProperties();
AzurePropertiesUtils.copyAzureCommonProperties(properties.getExtension(), containerProperties);
ProcessorPropertiesMerger.copyProcessorPropertiesIfNotNull(properties.getExtension(), containerProperties);
containerProperties.setEventHubName(destination.getName());
containerProperties.setConsumerGroup(group);
containerProperties.setCheckpointConfig(properties.getExtension().getCheckpoint());
return containerProperties;
}
@Override
public EventHubsConsumerProperties getExtendedConsumerProperties(String destination) {
return this.bindingProperties.getExtendedConsumerProperties(destination);
}
@Override
public EventHubsProducerProperties getExtendedProducerProperties(String destination) {
return this.bindingProperties.getExtendedProducerProperties(destination);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
/**
* Set binding properties.
*
* @param bindingProperties the binding properties
*/
public void setBindingProperties(EventHubsExtendedBindingProperties bindingProperties) {
this.bindingProperties = bindingProperties;
}
private PropertiesSupplier<String, ProducerProperties> getProducerPropertiesSupplier() {
return key -> {
if (this.extendedProducerPropertiesMap.containsKey(key)) {
EventHubsProducerProperties producerProperties = this.extendedProducerPropertiesMap.get(key)
.getExtension();
producerProperties.setEventHubName(key);
return producerProperties;
} else {
LOGGER.debug("Can't find extended properties for {}", key);
return null;
}
};
}
private EventHubsProcessorFactory getProcessorFactory() {
if (this.processorFactory == null) {
this.processorFactory = new DefaultEventHubsNamespaceProcessorFactory(
this.checkpointStore, this.namespaceProperties);
processorFactoryCustomizers.forEach(customizer -> customizer.customize(processorFactory));
processorFactory.addListener((name, consumerGroup, processorClient) -> {
String instrumentationName = name + "/" + consumerGroup;
Instrumentation instrumentation = new EventHubsProcessorInstrumentation(instrumentationName, CONSUMER, Duration.ofMinutes(2));
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
}
return this.processorFactory;
}
/**
* Set namespace properties.
*
* @param namespaceProperties the namespace properties
*/
public void setNamespaceProperties(NamespaceProperties namespaceProperties) {
this.namespaceProperties = namespaceProperties;
}
/**
* Set checkpoint store.
*
* @param checkpointStore the checkpoint store
*/
public void setCheckpointStore(CheckpointStore checkpointStore) {
this.checkpointStore = checkpointStore;
}
/**
* Get instrumentation manager.
*
* @return instrumentationManager the instrumentation manager
* @see InstrumentationManager
*/
InstrumentationManager getInstrumentationManager() {
return instrumentationManager;
}
/**
* Set the producer factory customizers.
*
* @param producerFactoryCustomizers The producer factory customizers.
*/
public void setProducerFactoryCustomizers(List<EventHubsProducerFactoryCustomizer> producerFactoryCustomizers) {
this.producerFactoryCustomizers = producerFactoryCustomizers;
}
/**
* Set the processor factory customizers.
*
* @param processorFactoryCustomizers The processor factory customizers.
*/
public void setProcessorFactoryCustomizers(List<EventHubsProcessorFactoryCustomizer> processorFactoryCustomizers) {
this.processorFactoryCustomizers = processorFactoryCustomizers;
}
} |
We should use API instead of impl classes in APIs. | private EventHubsTemplate getEventHubTemplate() {
if (this.eventHubsTemplate == null) {
DefaultEventHubsNamespaceProducerFactory factory = new DefaultEventHubsNamespaceProducerFactory(
this.namespaceProperties, getProducerPropertiesSupplier());
producerFactoryCustomizers.forEach(customizer -> customizer.customize(factory));
factory.addListener((name, producerAsyncClient) -> {
DefaultInstrumentation instrumentation = new DefaultInstrumentation(name, PRODUCER);
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
this.eventHubsTemplate = new EventHubsTemplate(factory);
}
return this.eventHubsTemplate;
} | producerFactoryCustomizers.forEach(customizer -> customizer.customize(factory)); | private EventHubsTemplate getEventHubTemplate() {
if (this.eventHubsTemplate == null) {
DefaultEventHubsNamespaceProducerFactory factory = new DefaultEventHubsNamespaceProducerFactory(
this.namespaceProperties, getProducerPropertiesSupplier());
producerFactoryCustomizers.forEach(customizer -> customizer.customize(factory));
factory.addListener((name, producerAsyncClient) -> {
DefaultInstrumentation instrumentation = new DefaultInstrumentation(name, PRODUCER);
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
this.eventHubsTemplate = new EventHubsTemplate(factory);
}
return this.eventHubsTemplate;
} | class EventHubsMessageChannelBinder extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<EventHubsConsumerProperties>, ExtendedProducerProperties<EventHubsProducerProperties>, EventHubsChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, EventHubsConsumerProperties, EventHubsProducerProperties> {
private static final Logger LOGGER = LoggerFactory.getLogger(EventHubsMessageChannelBinder.class);
private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
private NamespaceProperties namespaceProperties;
private EventHubsTemplate eventHubsTemplate;
private CheckpointStore checkpointStore;
private DefaultEventHubsNamespaceProcessorFactory processorFactory;
private final List<EventHubsMessageListenerContainer> eventHubsMessageListenerContainers = new ArrayList<>();
private final InstrumentationManager instrumentationManager = new DefaultInstrumentationManager();
private EventHubsExtendedBindingProperties bindingProperties = new EventHubsExtendedBindingProperties();
private final Map<String, ExtendedProducerProperties<EventHubsProducerProperties>>
extendedProducerPropertiesMap = new ConcurrentHashMap<>();
private List<EventHubsProducerFactoryCustomizer> producerFactoryCustomizers = new ArrayList<>();
private List<EventHubsProcessorFactoryCustomizer> processorFactoryCustomizers = new ArrayList<>();
/**
* Construct a {@link EventHubsMessageChannelBinder} with the specified headers to embed and {@link EventHubsChannelProvisioner}.
*
* @param headersToEmbed the headers to embed
* @param provisioningProvider the provisioning provider
*/
public EventHubsMessageChannelBinder(String[] headersToEmbed, EventHubsChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(
ProducerDestination destination,
ExtendedProducerProperties<EventHubsProducerProperties> producerProperties,
MessageChannel errorChannel) {
extendedProducerPropertiesMap.put(destination.getName(), producerProperties);
Assert.notNull(getEventHubTemplate(), "eventHubsTemplate can't be null when create a producer");
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), this.eventHubsTemplate);
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout().toMillis());
handler.setSendFailureChannel(errorChannel);
String instrumentationId = Instrumentation.buildId(PRODUCER, destination.getName());
handler.setSendCallback(new InstrumentationSendCallback(instrumentationId, instrumentationManager));
if (producerProperties.isPartitioned()) {
handler.setPartitionIdExpression(
EXPRESSION_PARSER.parseExpression("headers['" + BinderHeaders.PARTITION_HEADER + "']"));
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
Assert.notNull(getProcessorFactory(), "processor factory can't be null when create a consumer");
boolean anonymous = !StringUtils.hasText(group);
if (anonymous) {
group = "anonymous." + UUID.randomUUID();
}
EventHubsContainerProperties containerProperties = createContainerProperties(destination, group, properties);
EventHubsMessageListenerContainer listenerContainer = new EventHubsMessageListenerContainer(
getProcessorFactory(), containerProperties);
this.eventHubsMessageListenerContainers.add(listenerContainer);
EventHubsInboundChannelAdapter inboundAdapter;
if (properties.isBatchMode()) {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer, ListenerMode.BATCH);
} else {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer);
}
inboundAdapter.setBeanFactory(getBeanFactory());
String instrumentationId = Instrumentation.buildId(CONSUMER, destination.getName() + "/" + group);
inboundAdapter.setInstrumentationManager(instrumentationManager);
inboundAdapter.setInstrumentationId(instrumentationId);
ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties);
inboundAdapter.setErrorChannel(errorInfrastructure.getErrorChannel());
return inboundAdapter;
}
/**
* Create {@link EventHubsContainerProperties} from the extended {@link EventHubsConsumerProperties}.
* @param destination reference to the consumer destination.
* @param group the consumer group.
* @param properties the consumer properties.
* @return the {@link EventHubsContainerProperties}.
*/
private EventHubsContainerProperties createContainerProperties(
ConsumerDestination destination,
String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
EventHubsContainerProperties containerProperties = new EventHubsContainerProperties();
AzurePropertiesUtils.copyAzureCommonProperties(properties.getExtension(), containerProperties);
ProcessorPropertiesMerger.copyProcessorPropertiesIfNotNull(properties.getExtension(), containerProperties);
containerProperties.setEventHubName(destination.getName());
containerProperties.setConsumerGroup(group);
containerProperties.setCheckpointConfig(properties.getExtension().getCheckpoint());
return containerProperties;
}
@Override
public EventHubsConsumerProperties getExtendedConsumerProperties(String destination) {
return this.bindingProperties.getExtendedConsumerProperties(destination);
}
@Override
public EventHubsProducerProperties getExtendedProducerProperties(String destination) {
return this.bindingProperties.getExtendedProducerProperties(destination);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
/**
* Set binding properties.
*
* @param bindingProperties the binding properties
*/
public void setBindingProperties(EventHubsExtendedBindingProperties bindingProperties) {
this.bindingProperties = bindingProperties;
}
private PropertiesSupplier<String, ProducerProperties> getProducerPropertiesSupplier() {
return key -> {
if (this.extendedProducerPropertiesMap.containsKey(key)) {
EventHubsProducerProperties producerProperties = this.extendedProducerPropertiesMap.get(key)
.getExtension();
producerProperties.setEventHubName(key);
return producerProperties;
} else {
LOGGER.debug("Can't find extended properties for {}", key);
return null;
}
};
}
private EventHubsProcessorFactory getProcessorFactory() {
if (this.processorFactory == null) {
this.processorFactory = new DefaultEventHubsNamespaceProcessorFactory(
this.checkpointStore, this.namespaceProperties);
processorFactoryCustomizers.forEach(customizer -> customizer.customize(processorFactory));
processorFactory.addListener((name, consumerGroup, processorClient) -> {
String instrumentationName = name + "/" + consumerGroup;
Instrumentation instrumentation = new EventHubsProcessorInstrumentation(instrumentationName, CONSUMER, Duration.ofMinutes(2));
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
}
return this.processorFactory;
}
/**
* Set namespace properties.
*
* @param namespaceProperties the namespace properties
*/
public void setNamespaceProperties(NamespaceProperties namespaceProperties) {
this.namespaceProperties = namespaceProperties;
}
/**
* Set checkpoint store.
*
* @param checkpointStore the checkpoint store
*/
public void setCheckpointStore(CheckpointStore checkpointStore) {
this.checkpointStore = checkpointStore;
}
/**
* Get instrumentation manager.
*
* @return instrumentationManager the instrumentation manager
* @see InstrumentationManager
*/
InstrumentationManager getInstrumentationManager() {
return instrumentationManager;
}
/**
* Set the producer factory customizers.
*
* @param producerFactoryCustomizers The producer factory customizers.
*/
public void setProducerFactoryCustomizers(List<EventHubsProducerFactoryCustomizer> producerFactoryCustomizers) {
this.producerFactoryCustomizers = producerFactoryCustomizers;
}
/**
* Set the processor factory customizers.
*
* @param processorFactoryCustomizers The processor factory customizers.
*/
public void setProcessorFactoryCustomizers(List<EventHubsProcessorFactoryCustomizer> processorFactoryCustomizers) {
this.processorFactoryCustomizers = processorFactoryCustomizers;
}
} | class EventHubsMessageChannelBinder extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<EventHubsConsumerProperties>, ExtendedProducerProperties<EventHubsProducerProperties>, EventHubsChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, EventHubsConsumerProperties, EventHubsProducerProperties> {
private static final Logger LOGGER = LoggerFactory.getLogger(EventHubsMessageChannelBinder.class);
private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
private NamespaceProperties namespaceProperties;
private EventHubsTemplate eventHubsTemplate;
private CheckpointStore checkpointStore;
private DefaultEventHubsNamespaceProcessorFactory processorFactory;
private final List<EventHubsMessageListenerContainer> eventHubsMessageListenerContainers = new ArrayList<>();
private final InstrumentationManager instrumentationManager = new DefaultInstrumentationManager();
private EventHubsExtendedBindingProperties bindingProperties = new EventHubsExtendedBindingProperties();
private final Map<String, ExtendedProducerProperties<EventHubsProducerProperties>>
extendedProducerPropertiesMap = new ConcurrentHashMap<>();
private List<EventHubsProducerFactoryCustomizer> producerFactoryCustomizers = new ArrayList<>();
private List<EventHubsProcessorFactoryCustomizer> processorFactoryCustomizers = new ArrayList<>();
/**
* Construct a {@link EventHubsMessageChannelBinder} with the specified headers to embed and {@link EventHubsChannelProvisioner}.
*
* @param headersToEmbed the headers to embed
* @param provisioningProvider the provisioning provider
*/
public EventHubsMessageChannelBinder(String[] headersToEmbed, EventHubsChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(
ProducerDestination destination,
ExtendedProducerProperties<EventHubsProducerProperties> producerProperties,
MessageChannel errorChannel) {
extendedProducerPropertiesMap.put(destination.getName(), producerProperties);
Assert.notNull(getEventHubTemplate(), "eventHubsTemplate can't be null when create a producer");
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), this.eventHubsTemplate);
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout().toMillis());
handler.setSendFailureChannel(errorChannel);
String instrumentationId = Instrumentation.buildId(PRODUCER, destination.getName());
handler.setSendCallback(new InstrumentationSendCallback(instrumentationId, instrumentationManager));
if (producerProperties.isPartitioned()) {
handler.setPartitionIdExpression(
EXPRESSION_PARSER.parseExpression("headers['" + BinderHeaders.PARTITION_HEADER + "']"));
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
Assert.notNull(getProcessorFactory(), "processor factory can't be null when create a consumer");
boolean anonymous = !StringUtils.hasText(group);
if (anonymous) {
group = "anonymous." + UUID.randomUUID();
}
EventHubsContainerProperties containerProperties = createContainerProperties(destination, group, properties);
EventHubsMessageListenerContainer listenerContainer = new EventHubsMessageListenerContainer(
getProcessorFactory(), containerProperties);
this.eventHubsMessageListenerContainers.add(listenerContainer);
EventHubsInboundChannelAdapter inboundAdapter;
if (properties.isBatchMode()) {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer, ListenerMode.BATCH);
} else {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer);
}
inboundAdapter.setBeanFactory(getBeanFactory());
String instrumentationId = Instrumentation.buildId(CONSUMER, destination.getName() + "/" + group);
inboundAdapter.setInstrumentationManager(instrumentationManager);
inboundAdapter.setInstrumentationId(instrumentationId);
ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties);
inboundAdapter.setErrorChannel(errorInfrastructure.getErrorChannel());
return inboundAdapter;
}
/**
* Create {@link EventHubsContainerProperties} from the extended {@link EventHubsConsumerProperties}.
* @param destination reference to the consumer destination.
* @param group the consumer group.
* @param properties the consumer properties.
* @return the {@link EventHubsContainerProperties}.
*/
private EventHubsContainerProperties createContainerProperties(
ConsumerDestination destination,
String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
EventHubsContainerProperties containerProperties = new EventHubsContainerProperties();
AzurePropertiesUtils.copyAzureCommonProperties(properties.getExtension(), containerProperties);
ProcessorPropertiesMerger.copyProcessorPropertiesIfNotNull(properties.getExtension(), containerProperties);
containerProperties.setEventHubName(destination.getName());
containerProperties.setConsumerGroup(group);
containerProperties.setCheckpointConfig(properties.getExtension().getCheckpoint());
return containerProperties;
}
@Override
public EventHubsConsumerProperties getExtendedConsumerProperties(String destination) {
return this.bindingProperties.getExtendedConsumerProperties(destination);
}
@Override
public EventHubsProducerProperties getExtendedProducerProperties(String destination) {
return this.bindingProperties.getExtendedProducerProperties(destination);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
/**
* Set binding properties.
*
* @param bindingProperties the binding properties
*/
public void setBindingProperties(EventHubsExtendedBindingProperties bindingProperties) {
this.bindingProperties = bindingProperties;
}
private PropertiesSupplier<String, ProducerProperties> getProducerPropertiesSupplier() {
return key -> {
if (this.extendedProducerPropertiesMap.containsKey(key)) {
EventHubsProducerProperties producerProperties = this.extendedProducerPropertiesMap.get(key)
.getExtension();
producerProperties.setEventHubName(key);
return producerProperties;
} else {
LOGGER.debug("Can't find extended properties for {}", key);
return null;
}
};
}
private EventHubsProcessorFactory getProcessorFactory() {
if (this.processorFactory == null) {
this.processorFactory = new DefaultEventHubsNamespaceProcessorFactory(
this.checkpointStore, this.namespaceProperties);
processorFactoryCustomizers.forEach(customizer -> customizer.customize(processorFactory));
processorFactory.addListener((name, consumerGroup, processorClient) -> {
String instrumentationName = name + "/" + consumerGroup;
Instrumentation instrumentation = new EventHubsProcessorInstrumentation(instrumentationName, CONSUMER, Duration.ofMinutes(2));
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
}
return this.processorFactory;
}
/**
* Set namespace properties.
*
* @param namespaceProperties the namespace properties
*/
public void setNamespaceProperties(NamespaceProperties namespaceProperties) {
this.namespaceProperties = namespaceProperties;
}
/**
* Set checkpoint store.
*
* @param checkpointStore the checkpoint store
*/
public void setCheckpointStore(CheckpointStore checkpointStore) {
this.checkpointStore = checkpointStore;
}
/**
* Get instrumentation manager.
*
* @return instrumentationManager the instrumentation manager
* @see InstrumentationManager
*/
InstrumentationManager getInstrumentationManager() {
return instrumentationManager;
}
/**
* Set the producer factory customizers.
*
* @param producerFactoryCustomizers The producer factory customizers.
*/
public void setProducerFactoryCustomizers(List<EventHubsProducerFactoryCustomizer> producerFactoryCustomizers) {
this.producerFactoryCustomizers = producerFactoryCustomizers;
}
/**
* Set the processor factory customizers.
*
* @param processorFactoryCustomizers The processor factory customizers.
*/
public void setProcessorFactoryCustomizers(List<EventHubsProcessorFactoryCustomizer> processorFactoryCustomizers) {
this.processorFactoryCustomizers = processorFactoryCustomizers;
}
} |
This is neat, I wish `mocha` had something like that... | public void getKeyRotationPolicyOfNonExistentKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
Assumptions.assumeTrue(!isHsmEnabled);
createKeyClient(httpClient, serviceVersion);
String keyName = testResourceNamer.randomName("nonExistentKey", 20);
assertThrows(ResourceNotFoundException.class, () -> client.getKeyRotationPolicy(keyName));
} | Assumptions.assumeTrue(!isHsmEnabled); | public void getKeyRotationPolicyOfNonExistentKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
Assumptions.assumeTrue(!isHsmEnabled);
createKeyClient(httpClient, serviceVersion);
String keyName = testResourceNamer.randomName("nonExistentKey", 20);
assertThrows(ResourceNotFoundException.class, () -> client.getKeyRotationPolicy(keyName));
} | class KeyClientTest extends KeyClientTestBase {
protected KeyClient client;
@Override
protected void beforeTest() {
beforeTestSetup();
}
protected void createKeyClient(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion, null);
}
protected void createKeyClient(HttpClient httpClient, KeyServiceVersion serviceVersion, String testTenantId) {
HttpPipeline httpPipeline = getHttpPipeline(httpClient, testTenantId);
KeyAsyncClient asyncClient = spy(new KeyClientBuilder()
.vaultUrl(getEndpoint())
.pipeline(httpPipeline)
.serviceVersion(serviceVersion)
.buildAsyncClient());
if (interceptorManager.isPlaybackMode()) {
when(asyncClient.getDefaultPollingInterval()).thenReturn(Duration.ofMillis(10));
}
client = new KeyClient(asyncClient);
}
/**
* Tests that a key can be created in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void setKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
setKeyRunner((expected) -> assertKeyEquals(expected, client.createKey(expected)));
}
/**
* Tests that a key can be created in the key vault while using a different tenant ID than the one that will be
* provided in the authentication challenge.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void setKeyWithMultipleTenants(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion, testResourceNamer.randomUuid());
setKeyRunner((expected) -> assertKeyEquals(expected, client.createKey(expected)));
KeyVaultCredentialPolicy.clearCache();
setKeyRunner((expected) -> assertKeyEquals(expected, client.createKey(expected)));
}
/**
* Tests that an RSA key is created.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
createRsaKeyRunner((expected) -> assertKeyEquals(expected, client.createRsaKey(expected)));
}
/**
* Tests that an attempt to create a key with empty string name throws an error.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void setKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
final KeyType keyType;
if (runManagedHsmTest) {
keyType = KeyType.RSA_HSM;
} else {
keyType = KeyType.RSA;
}
assertRestException(() -> client.createKey("", keyType), ResourceModifiedException.class,
HttpURLConnection.HTTP_BAD_REQUEST);
}
/**
* Tests that we cannot create keys when key type is null.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void setKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
setKeyEmptyValueRunner((key) -> {
assertRestException(() -> client.createKey(key.getName(), key.getKeyType()), ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST);
});
}
/**
* Verifies that an exception is thrown when null key object is passed for creation.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void setKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRunnableThrowsException(() -> client.createKey(null), NullPointerException.class);
assertRunnableThrowsException(() -> client.createKey(null), NullPointerException.class);
}
/**
* Tests that a key is able to be updated when it exists.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
updateKeyRunner((createKeyOptions, updateKeyOptions) -> {
KeyVaultKey createdKey = client.createKey(createKeyOptions);
assertKeyEquals(createKeyOptions, createdKey);
KeyVaultKey updatedKey =
client.updateKeyProperties(createdKey.getProperties().setExpiresOn(updateKeyOptions.getExpiresOn()));
assertKeyEquals(updateKeyOptions, updatedKey);
});
}
/**
* Tests that a key is able to be updated when it is disabled.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
updateDisabledKeyRunner((createKeyOptions, updateKeyOptions) -> {
KeyVaultKey createdKey = client.createKey(createKeyOptions);
assertKeyEquals(createKeyOptions, createdKey);
KeyVaultKey updatedKey =
client.updateKeyProperties(createdKey.getProperties().setExpiresOn(updateKeyOptions.getExpiresOn()));
assertKeyEquals(updateKeyOptions, updatedKey);
});
}
/**
* Tests that an existing key can be retrieved.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
getKeyRunner((original) -> {
client.createKey(original);
assertKeyEquals(original, client.getKey(original.getName()));
});
}
/**
* Tests that a specific version of the key can be retrieved.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
getKeySpecificVersionRunner((key, keyWithNewVal) -> {
KeyVaultKey keyVersionOne = client.createKey(key);
KeyVaultKey keyVersionTwo = client.createKey(keyWithNewVal);
assertKeyEquals(key, client.getKey(keyVersionOne.getName(), keyVersionOne.getProperties().getVersion()));
assertKeyEquals(keyWithNewVal, client.getKey(keyVersionTwo.getName(), keyVersionTwo.getProperties().getVersion()));
});
}
/**
* Tests that an attempt to get a non-existing key throws an error.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRestException(() -> client.getKey("non-existing"), ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND);
}
/**
* Tests that an existing key can be deleted.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
deleteKeyRunner((keyToDelete) -> {
sleepInRecordMode(30000);
assertKeyEquals(keyToDelete, client.createKey(keyToDelete));
SyncPoller<DeletedKey, Void> deletedKeyPoller = client.beginDeleteKey(keyToDelete.getName());
PollResponse<DeletedKey> pollResponse = deletedKeyPoller.poll();
DeletedKey deletedKey = pollResponse.getValue();
while (!pollResponse.getStatus().isComplete()) {
sleepInRecordMode(10000);
pollResponse = deletedKeyPoller.poll();
}
assertNotNull(deletedKey.getDeletedOn());
assertNotNull(deletedKey.getRecoveryId());
assertNotNull(deletedKey.getScheduledPurgeDate());
assertEquals(keyToDelete.getName(), deletedKey.getName());
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRestException(() -> client.beginDeleteKey("non-existing"), ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND);
}
/**
* Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRestException(() -> client.getDeletedKey("non-existing"), ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND);
}
/**
* Tests that a deleted key can be recovered on a soft-delete enabled vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
recoverDeletedKeyRunner((keyToDeleteAndRecover) -> {
assertKeyEquals(keyToDeleteAndRecover, client.createKey(keyToDeleteAndRecover));
SyncPoller<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndRecover.getName());
PollResponse<DeletedKey> pollResponse = poller.poll();
while (!pollResponse.getStatus().isComplete()) {
sleepInRecordMode(1000);
pollResponse = poller.poll();
}
assertNotNull(pollResponse.getValue());
SyncPoller<KeyVaultKey, Void> recoverPoller = client.beginRecoverDeletedKey(keyToDeleteAndRecover.getName());
PollResponse<KeyVaultKey> recoverPollResponse = recoverPoller.poll();
KeyVaultKey recoveredKey = recoverPollResponse.getValue();
recoverPollResponse = recoverPoller.poll();
while (!recoverPollResponse.getStatus().isComplete()) {
sleepInRecordMode(1000);
recoverPollResponse = recoverPoller.poll();
}
assertEquals(keyToDeleteAndRecover.getName(), recoveredKey.getName());
assertEquals(keyToDeleteAndRecover.getNotBefore(), recoveredKey.getProperties().getNotBefore());
assertEquals(keyToDeleteAndRecover.getExpiresOn(), recoveredKey.getProperties().getExpiresOn());
});
}
/**
* Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRestException(() -> client.beginRecoverDeletedKey("non-existing"), ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND);
}
/**
* Tests that a key can be backed up in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
backupKeyRunner((keyToBackup) -> {
assertKeyEquals(keyToBackup, client.createKey(keyToBackup));
byte[] backupBytes = (client.backupKey(keyToBackup.getName()));
assertNotNull(backupBytes);
assertTrue(backupBytes.length > 0);
});
}
/**
* Tests that an attempt to backup a non existing key throws an error.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRestException(() -> client.backupKey("non-existing"), ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND);
}
/**
* Tests that a key can be backed up in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
restoreKeyRunner((keyToBackupAndRestore) -> {
assertKeyEquals(keyToBackupAndRestore, client.createKey(keyToBackupAndRestore));
byte[] backupBytes = (client.backupKey(keyToBackupAndRestore.getName()));
assertNotNull(backupBytes);
assertTrue(backupBytes.length > 0);
SyncPoller<DeletedKey, Void> poller = client.beginDeleteKey(keyToBackupAndRestore.getName());
PollResponse<DeletedKey> pollResponse = poller.poll();
while (!pollResponse.getStatus().isComplete()) {
sleepInRecordMode(1000);
pollResponse = poller.poll();
}
client.purgeDeletedKey(keyToBackupAndRestore.getName());
pollOnKeyPurge(keyToBackupAndRestore.getName());
sleepInRecordMode(60000);
KeyVaultKey restoredKey = client.restoreKeyBackup(backupBytes);
assertEquals(keyToBackupAndRestore.getName(), restoredKey.getName());
assertEquals(keyToBackupAndRestore.getExpiresOn(), restoredKey.getProperties().getExpiresOn());
});
}
/**
* Tests that an attempt to restore a key from malformed backup bytes throws an error.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
byte[] keyBackupBytes = "non-existing".getBytes();
assertRestException(() -> client.restoreKeyBackup(keyBackupBytes), ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST);
}
/**
* Tests that keys can be listed in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
listKeysRunner((keys) -> {
HashMap<String, CreateKeyOptions> keysToList = keys;
for (CreateKeyOptions key : keysToList.values()) {
assertKeyEquals(key, client.createKey(key));
sleepInRecordMode(5000);
}
for (KeyProperties actualKey : client.listPropertiesOfKeys()) {
if (keys.containsKey(actualKey.getName())) {
CreateKeyOptions expectedKey = keys.get(actualKey.getName());
assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn());
assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore());
keys.remove(actualKey.getName());
}
}
assertEquals(0, keys.size());
});
}
/**
* Tests that a deleted key can be retrieved on a soft-delete enabled vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
getDeletedKeyRunner((keyToDeleteAndGet) -> {
assertKeyEquals(keyToDeleteAndGet, client.createKey(keyToDeleteAndGet));
SyncPoller<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndGet.getName());
PollResponse<DeletedKey> pollResponse = poller.poll();
while (!pollResponse.getStatus().isComplete()) {
sleepInRecordMode(1000);
pollResponse = poller.poll();
}
sleepInRecordMode(30000);
DeletedKey deletedKey = client.getDeletedKey(keyToDeleteAndGet.getName());
assertNotNull(deletedKey.getDeletedOn());
assertNotNull(deletedKey.getRecoveryId());
assertNotNull(deletedKey.getScheduledPurgeDate());
assertEquals(keyToDeleteAndGet.getName(), deletedKey.getName());
});
}
/**
* Tests that deleted keys can be listed in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
if (!interceptorManager.isPlaybackMode()) {
return;
}
listDeletedKeysRunner((keys) -> {
HashMap<String, CreateKeyOptions> keysToDelete = keys;
for (CreateKeyOptions key : keysToDelete.values()) {
assertKeyEquals(key, client.createKey(key));
}
for (CreateKeyOptions key : keysToDelete.values()) {
SyncPoller<DeletedKey, Void> poller = client.beginDeleteKey(key.getName());
PollResponse<DeletedKey> pollResponse = poller.poll();
while (!pollResponse.getStatus().isComplete()) {
sleepInRecordMode(1000);
pollResponse = poller.poll();
}
}
sleepInRecordMode(90000);
Iterable<DeletedKey> deletedKeys = client.listDeletedKeys();
for (DeletedKey deletedKey : deletedKeys) {
assertNotNull(deletedKey.getDeletedOn());
assertNotNull(deletedKey.getRecoveryId());
}
});
}
/**
* Tests that key versions can be listed in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
listKeyVersionsRunner((keys) -> {
List<CreateKeyOptions> keyVersions = keys;
String keyName = null;
for (CreateKeyOptions key : keyVersions) {
keyName = key.getName();
sleepInRecordMode(4000);
assertKeyEquals(key, client.createKey(key));
}
Iterable<KeyProperties> keyVersionsOutput = client.listPropertiesOfKeyVersions(keyName);
List<KeyProperties> keyVersionsList = new ArrayList<>();
keyVersionsOutput.forEach(keyVersionsList::add);
assertEquals(keyVersions.size(), keyVersionsList.size());
});
}
/**
* Tests that an existing key can be released.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
Assumptions.assumeTrue(runManagedHsmTest);
createKeyClient(httpClient, serviceVersion);
releaseKeyRunner((keyToRelease, attestationUrl) -> {
assertKeyEquals(keyToRelease, client.createRsaKey(keyToRelease));
String targetAttestationToken = "testAttestationToken";
if (getTestMode() != TestMode.PLAYBACK) {
if (!attestationUrl.endsWith("/")) {
attestationUrl = attestationUrl + "/";
}
try {
targetAttestationToken = getAttestationToken(attestationUrl + "generate-test-token");
} catch (IOException e) {
fail("Found error when deserializing attestation token.", e);
}
}
ReleaseKeyResult releaseKeyResult = client.releaseKey(keyToRelease.getName(), targetAttestationToken);
assertNotNull(releaseKeyResult.getValue());
});
}
/**
* Tests that fetching the key rotation policy of a non-existent key throws.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
@DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true")
/**
* Tests that fetching the key rotation policy of a non-existent key throws.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
@DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true")
public void getKeyRotationPolicyWithNoPolicySet(HttpClient httpClient, KeyServiceVersion serviceVersion) {
Assumptions.assumeTrue(!isHsmEnabled);
createKeyClient(httpClient, serviceVersion);
String keyName = testResourceNamer.randomName("rotateKey", 20);
client.createRsaKey(new CreateRsaKeyOptions(keyName));
KeyRotationPolicy keyRotationPolicy = client.getKeyRotationPolicy(keyName);
assertNotNull(keyRotationPolicy);
assertNull(keyRotationPolicy.getId());
assertNull(keyRotationPolicy.getCreatedOn());
assertNull(keyRotationPolicy.getUpdatedOn());
assertNull(keyRotationPolicy.getExpiresIn());
assertEquals(1, keyRotationPolicy.getLifetimeActions().size());
assertEquals(KeyRotationPolicyAction.NOTIFY, keyRotationPolicy.getLifetimeActions().get(0).getAction());
assertEquals("P30D", keyRotationPolicy.getLifetimeActions().get(0).getTimeBeforeExpiry());
assertNull(keyRotationPolicy.getLifetimeActions().get(0).getTimeAfterCreate());
}
/**
* Tests that fetching the key rotation policy of a non-existent key throws.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
@DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true")
public void updateGetKeyRotationPolicyWithMinimumProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) {
Assumptions.assumeTrue(!isHsmEnabled);
createKeyClient(httpClient, serviceVersion);
updateGetKeyRotationPolicyWithMinimumPropertiesRunner((keyName, keyRotationPolicy) -> {
client.createRsaKey(new CreateRsaKeyOptions(keyName));
KeyRotationPolicy updatedKeyRotationPolicy =
client.updateKeyRotationPolicy(keyName, keyRotationPolicy);
KeyRotationPolicy retrievedKeyRotationPolicy = client.getKeyRotationPolicy(keyName);
assertKeyVaultRotationPolicyEquals(updatedKeyRotationPolicy, retrievedKeyRotationPolicy);
});
}
/**
* Tests that an key rotation policy can be updated with all possible properties, then retrieves it.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
@DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true")
public void updateGetKeyRotationPolicyWithAllProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) {
Assumptions.assumeTrue(!isHsmEnabled);
createKeyClient(httpClient, serviceVersion);
updateGetKeyRotationPolicyWithAllPropertiesRunner((keyName, keyRotationPolicy) -> {
client.createRsaKey(new CreateRsaKeyOptions(keyName));
KeyRotationPolicy updatedKeyRotationPolicy =
client.updateKeyRotationPolicy(keyName, keyRotationPolicy);
KeyRotationPolicy retrievedKeyRotationPolicy = client.getKeyRotationPolicy(keyName);
assertKeyVaultRotationPolicyEquals(updatedKeyRotationPolicy, retrievedKeyRotationPolicy);
});
}
/**
* Tests that a key can be rotated.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
@DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true")
public void rotateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
Assumptions.assumeTrue(!isHsmEnabled);
createKeyClient(httpClient, serviceVersion);
String keyName = testResourceNamer.randomName("rotateKey", 20);
KeyVaultKey createdKey = client.createRsaKey(new CreateRsaKeyOptions(keyName));
KeyVaultKey rotatedKey = client.rotateKey(keyName);
assertEquals(createdKey.getName(), rotatedKey.getName());
assertEquals(createdKey.getProperties().getTags(), rotatedKey.getProperties().getTags());
}
/**
* Tests that a {@link CryptographyClient} can be created for a given key and version using a {@link KeyClient}.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getCryptographyClient(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
CryptographyClient cryptographyClient = client.getCryptographyClient("myKey");
assertNotNull(cryptographyClient);
}
/**
* Tests that a {@link CryptographyClient} can be created for a given key using a {@link KeyClient}. Also tests
* that cryptographic operations can be performed with said cryptography client.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getCryptographyClientAndEncryptDecrypt(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
setKeyRunner((createKeyOptions) -> {
assertKeyEquals(createKeyOptions, client.createKey(createKeyOptions));
CryptographyClient cryptographyClient = client.getCryptographyClient(createKeyOptions.getName());
assertNotNull(cryptographyClient);
byte[] plaintext = "myPlaintext".getBytes();
byte[] ciphertext = cryptographyClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext).getCipherText();
byte[] decryptedText = cryptographyClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext).getPlainText();
assertArrayEquals(plaintext, decryptedText);
});
}
/**
* Tests that a {@link CryptographyClient} can be created for a given key and version using a {@link KeyClient}.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getCryptographyClientWithKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
CryptographyClient cryptographyClient =
client.getCryptographyClient("myKey", "6A385B124DEF4096AF1361A85B16C204");
assertNotNull(cryptographyClient);
}
/**
* Tests that a {@link CryptographyClient} can be created for a given key using a {@link KeyClient}.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getCryptographyClientWithEmptyKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
CryptographyClient cryptographyClient = client.getCryptographyClient("myKey", "");
assertNotNull(cryptographyClient);
}
/**
* Tests that a {@link CryptographyClient} can be created for a given key using a {@link KeyClient}.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getCryptographyClientWithNullKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
CryptographyClient cryptographyClient = client.getCryptographyClient("myKey", null);
assertNotNull(cryptographyClient);
}
private void pollOnKeyPurge(String keyName) {
int pendingPollCount = 0;
while (pendingPollCount < 10) {
DeletedKey deletedKey = null;
try {
deletedKey = client.getDeletedKey(keyName);
} catch (ResourceNotFoundException e) {
}
if (deletedKey != null) {
sleepInRecordMode(2000);
pendingPollCount += 1;
continue;
} else {
return;
}
}
System.err.printf("Deleted Key %s was not purged \n", keyName);
}
} | class KeyClientTest extends KeyClientTestBase {
protected KeyClient client;
@Override
protected void beforeTest() {
beforeTestSetup();
}
protected void createKeyClient(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion, null);
}
protected void createKeyClient(HttpClient httpClient, KeyServiceVersion serviceVersion, String testTenantId) {
HttpPipeline httpPipeline = getHttpPipeline(httpClient, testTenantId);
KeyAsyncClient asyncClient = spy(new KeyClientBuilder()
.vaultUrl(getEndpoint())
.pipeline(httpPipeline)
.serviceVersion(serviceVersion)
.buildAsyncClient());
if (interceptorManager.isPlaybackMode()) {
when(asyncClient.getDefaultPollingInterval()).thenReturn(Duration.ofMillis(10));
}
client = new KeyClient(asyncClient);
}
/**
* Tests that a key can be created in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void setKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
setKeyRunner((expected) -> assertKeyEquals(expected, client.createKey(expected)));
}
/**
* Tests that a key can be created in the key vault while using a different tenant ID than the one that will be
* provided in the authentication challenge.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void setKeyWithMultipleTenants(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion, testResourceNamer.randomUuid());
setKeyRunner((expected) -> assertKeyEquals(expected, client.createKey(expected)));
KeyVaultCredentialPolicy.clearCache();
setKeyRunner((expected) -> assertKeyEquals(expected, client.createKey(expected)));
}
/**
* Tests that an RSA key is created.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
createRsaKeyRunner((expected) -> assertKeyEquals(expected, client.createRsaKey(expected)));
}
/**
* Tests that an attempt to create a key with empty string name throws an error.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void setKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
final KeyType keyType;
if (runManagedHsmTest) {
keyType = KeyType.RSA_HSM;
} else {
keyType = KeyType.RSA;
}
assertRestException(() -> client.createKey("", keyType), ResourceModifiedException.class,
HttpURLConnection.HTTP_BAD_REQUEST);
}
/**
* Tests that we cannot create keys when key type is null.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void setKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
setKeyEmptyValueRunner((key) -> {
assertRestException(() -> client.createKey(key.getName(), key.getKeyType()), ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST);
});
}
/**
* Verifies that an exception is thrown when null key object is passed for creation.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void setKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRunnableThrowsException(() -> client.createKey(null), NullPointerException.class);
assertRunnableThrowsException(() -> client.createKey(null), NullPointerException.class);
}
/**
* Tests that a key is able to be updated when it exists.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
updateKeyRunner((createKeyOptions, updateKeyOptions) -> {
KeyVaultKey createdKey = client.createKey(createKeyOptions);
assertKeyEquals(createKeyOptions, createdKey);
KeyVaultKey updatedKey =
client.updateKeyProperties(createdKey.getProperties().setExpiresOn(updateKeyOptions.getExpiresOn()));
assertKeyEquals(updateKeyOptions, updatedKey);
});
}
/**
* Tests that a key is able to be updated when it is disabled.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
updateDisabledKeyRunner((createKeyOptions, updateKeyOptions) -> {
KeyVaultKey createdKey = client.createKey(createKeyOptions);
assertKeyEquals(createKeyOptions, createdKey);
KeyVaultKey updatedKey =
client.updateKeyProperties(createdKey.getProperties().setExpiresOn(updateKeyOptions.getExpiresOn()));
assertKeyEquals(updateKeyOptions, updatedKey);
});
}
/**
* Tests that an existing key can be retrieved.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
getKeyRunner((original) -> {
client.createKey(original);
assertKeyEquals(original, client.getKey(original.getName()));
});
}
/**
* Tests that a specific version of the key can be retrieved.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
getKeySpecificVersionRunner((key, keyWithNewVal) -> {
KeyVaultKey keyVersionOne = client.createKey(key);
KeyVaultKey keyVersionTwo = client.createKey(keyWithNewVal);
assertKeyEquals(key, client.getKey(keyVersionOne.getName(), keyVersionOne.getProperties().getVersion()));
assertKeyEquals(keyWithNewVal, client.getKey(keyVersionTwo.getName(), keyVersionTwo.getProperties().getVersion()));
});
}
/**
* Tests that an attempt to get a non-existing key throws an error.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRestException(() -> client.getKey("non-existing"), ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND);
}
/**
* Tests that an existing key can be deleted.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
deleteKeyRunner((keyToDelete) -> {
sleepInRecordMode(30000);
assertKeyEquals(keyToDelete, client.createKey(keyToDelete));
SyncPoller<DeletedKey, Void> deletedKeyPoller = client.beginDeleteKey(keyToDelete.getName());
PollResponse<DeletedKey> pollResponse = deletedKeyPoller.poll();
DeletedKey deletedKey = pollResponse.getValue();
while (!pollResponse.getStatus().isComplete()) {
sleepInRecordMode(10000);
pollResponse = deletedKeyPoller.poll();
}
assertNotNull(deletedKey.getDeletedOn());
assertNotNull(deletedKey.getRecoveryId());
assertNotNull(deletedKey.getScheduledPurgeDate());
assertEquals(keyToDelete.getName(), deletedKey.getName());
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRestException(() -> client.beginDeleteKey("non-existing"), ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND);
}
/**
* Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRestException(() -> client.getDeletedKey("non-existing"), ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND);
}
/**
* Tests that a deleted key can be recovered on a soft-delete enabled vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
recoverDeletedKeyRunner((keyToDeleteAndRecover) -> {
assertKeyEquals(keyToDeleteAndRecover, client.createKey(keyToDeleteAndRecover));
SyncPoller<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndRecover.getName());
PollResponse<DeletedKey> pollResponse = poller.poll();
while (!pollResponse.getStatus().isComplete()) {
sleepInRecordMode(1000);
pollResponse = poller.poll();
}
assertNotNull(pollResponse.getValue());
SyncPoller<KeyVaultKey, Void> recoverPoller = client.beginRecoverDeletedKey(keyToDeleteAndRecover.getName());
PollResponse<KeyVaultKey> recoverPollResponse = recoverPoller.poll();
KeyVaultKey recoveredKey = recoverPollResponse.getValue();
recoverPollResponse = recoverPoller.poll();
while (!recoverPollResponse.getStatus().isComplete()) {
sleepInRecordMode(1000);
recoverPollResponse = recoverPoller.poll();
}
assertEquals(keyToDeleteAndRecover.getName(), recoveredKey.getName());
assertEquals(keyToDeleteAndRecover.getNotBefore(), recoveredKey.getProperties().getNotBefore());
assertEquals(keyToDeleteAndRecover.getExpiresOn(), recoveredKey.getProperties().getExpiresOn());
});
}
/**
* Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRestException(() -> client.beginRecoverDeletedKey("non-existing"), ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND);
}
/**
* Tests that a key can be backed up in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
backupKeyRunner((keyToBackup) -> {
assertKeyEquals(keyToBackup, client.createKey(keyToBackup));
byte[] backupBytes = (client.backupKey(keyToBackup.getName()));
assertNotNull(backupBytes);
assertTrue(backupBytes.length > 0);
});
}
/**
* Tests that an attempt to backup a non existing key throws an error.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRestException(() -> client.backupKey("non-existing"), ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND);
}
/**
* Tests that a key can be backed up in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
restoreKeyRunner((keyToBackupAndRestore) -> {
assertKeyEquals(keyToBackupAndRestore, client.createKey(keyToBackupAndRestore));
byte[] backupBytes = (client.backupKey(keyToBackupAndRestore.getName()));
assertNotNull(backupBytes);
assertTrue(backupBytes.length > 0);
SyncPoller<DeletedKey, Void> poller = client.beginDeleteKey(keyToBackupAndRestore.getName());
PollResponse<DeletedKey> pollResponse = poller.poll();
while (!pollResponse.getStatus().isComplete()) {
sleepInRecordMode(1000);
pollResponse = poller.poll();
}
client.purgeDeletedKey(keyToBackupAndRestore.getName());
pollOnKeyPurge(keyToBackupAndRestore.getName());
sleepInRecordMode(60000);
KeyVaultKey restoredKey = client.restoreKeyBackup(backupBytes);
assertEquals(keyToBackupAndRestore.getName(), restoredKey.getName());
assertEquals(keyToBackupAndRestore.getExpiresOn(), restoredKey.getProperties().getExpiresOn());
});
}
/**
* Tests that an attempt to restore a key from malformed backup bytes throws an error.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
byte[] keyBackupBytes = "non-existing".getBytes();
assertRestException(() -> client.restoreKeyBackup(keyBackupBytes), ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST);
}
/**
* Tests that keys can be listed in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
listKeysRunner((keys) -> {
HashMap<String, CreateKeyOptions> keysToList = keys;
for (CreateKeyOptions key : keysToList.values()) {
assertKeyEquals(key, client.createKey(key));
sleepInRecordMode(5000);
}
for (KeyProperties actualKey : client.listPropertiesOfKeys()) {
if (keys.containsKey(actualKey.getName())) {
CreateKeyOptions expectedKey = keys.get(actualKey.getName());
assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn());
assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore());
keys.remove(actualKey.getName());
}
}
assertEquals(0, keys.size());
});
}
/**
* Tests that a deleted key can be retrieved on a soft-delete enabled vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
getDeletedKeyRunner((keyToDeleteAndGet) -> {
assertKeyEquals(keyToDeleteAndGet, client.createKey(keyToDeleteAndGet));
SyncPoller<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndGet.getName());
PollResponse<DeletedKey> pollResponse = poller.poll();
while (!pollResponse.getStatus().isComplete()) {
sleepInRecordMode(1000);
pollResponse = poller.poll();
}
sleepInRecordMode(30000);
DeletedKey deletedKey = client.getDeletedKey(keyToDeleteAndGet.getName());
assertNotNull(deletedKey.getDeletedOn());
assertNotNull(deletedKey.getRecoveryId());
assertNotNull(deletedKey.getScheduledPurgeDate());
assertEquals(keyToDeleteAndGet.getName(), deletedKey.getName());
});
}
/**
* Tests that deleted keys can be listed in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
if (!interceptorManager.isPlaybackMode()) {
return;
}
listDeletedKeysRunner((keys) -> {
HashMap<String, CreateKeyOptions> keysToDelete = keys;
for (CreateKeyOptions key : keysToDelete.values()) {
assertKeyEquals(key, client.createKey(key));
}
for (CreateKeyOptions key : keysToDelete.values()) {
SyncPoller<DeletedKey, Void> poller = client.beginDeleteKey(key.getName());
PollResponse<DeletedKey> pollResponse = poller.poll();
while (!pollResponse.getStatus().isComplete()) {
sleepInRecordMode(1000);
pollResponse = poller.poll();
}
}
sleepInRecordMode(90000);
Iterable<DeletedKey> deletedKeys = client.listDeletedKeys();
for (DeletedKey deletedKey : deletedKeys) {
assertNotNull(deletedKey.getDeletedOn());
assertNotNull(deletedKey.getRecoveryId());
}
});
}
/**
* Tests that key versions can be listed in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
listKeyVersionsRunner((keys) -> {
List<CreateKeyOptions> keyVersions = keys;
String keyName = null;
for (CreateKeyOptions key : keyVersions) {
keyName = key.getName();
sleepInRecordMode(4000);
assertKeyEquals(key, client.createKey(key));
}
Iterable<KeyProperties> keyVersionsOutput = client.listPropertiesOfKeyVersions(keyName);
List<KeyProperties> keyVersionsList = new ArrayList<>();
keyVersionsOutput.forEach(keyVersionsList::add);
assertEquals(keyVersions.size(), keyVersionsList.size());
});
}
/**
* Tests that an existing key can be released.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
Assumptions.assumeTrue(runManagedHsmTest);
createKeyClient(httpClient, serviceVersion);
releaseKeyRunner((keyToRelease, attestationUrl) -> {
assertKeyEquals(keyToRelease, client.createRsaKey(keyToRelease));
String targetAttestationToken = "testAttestationToken";
if (getTestMode() != TestMode.PLAYBACK) {
if (!attestationUrl.endsWith("/")) {
attestationUrl = attestationUrl + "/";
}
try {
targetAttestationToken = getAttestationToken(attestationUrl + "generate-test-token");
} catch (IOException e) {
fail("Found error when deserializing attestation token.", e);
}
}
ReleaseKeyResult releaseKeyResult = client.releaseKey(keyToRelease.getName(), targetAttestationToken);
assertNotNull(releaseKeyResult.getValue());
});
}
/**
* Tests that fetching the key rotation policy of a non-existent key throws.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
@DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true")
/**
* Tests that fetching the key rotation policy of a non-existent key throws.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
@DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true")
public void getKeyRotationPolicyWithNoPolicySet(HttpClient httpClient, KeyServiceVersion serviceVersion) {
Assumptions.assumeTrue(!isHsmEnabled);
createKeyClient(httpClient, serviceVersion);
String keyName = testResourceNamer.randomName("rotateKey", 20);
client.createRsaKey(new CreateRsaKeyOptions(keyName));
KeyRotationPolicy keyRotationPolicy = client.getKeyRotationPolicy(keyName);
assertNotNull(keyRotationPolicy);
assertNull(keyRotationPolicy.getId());
assertNull(keyRotationPolicy.getCreatedOn());
assertNull(keyRotationPolicy.getUpdatedOn());
assertNull(keyRotationPolicy.getExpiresIn());
assertEquals(1, keyRotationPolicy.getLifetimeActions().size());
assertEquals(KeyRotationPolicyAction.NOTIFY, keyRotationPolicy.getLifetimeActions().get(0).getAction());
assertEquals("P30D", keyRotationPolicy.getLifetimeActions().get(0).getTimeBeforeExpiry());
assertNull(keyRotationPolicy.getLifetimeActions().get(0).getTimeAfterCreate());
}
/**
* Tests that fetching the key rotation policy of a non-existent key throws.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
@DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true")
public void updateGetKeyRotationPolicyWithMinimumProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) {
Assumptions.assumeTrue(!isHsmEnabled);
createKeyClient(httpClient, serviceVersion);
updateGetKeyRotationPolicyWithMinimumPropertiesRunner((keyName, keyRotationPolicy) -> {
client.createRsaKey(new CreateRsaKeyOptions(keyName));
KeyRotationPolicy updatedKeyRotationPolicy =
client.updateKeyRotationPolicy(keyName, keyRotationPolicy);
KeyRotationPolicy retrievedKeyRotationPolicy = client.getKeyRotationPolicy(keyName);
assertKeyVaultRotationPolicyEquals(updatedKeyRotationPolicy, retrievedKeyRotationPolicy);
});
}
/**
* Tests that an key rotation policy can be updated with all possible properties, then retrieves it.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
@DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true")
public void updateGetKeyRotationPolicyWithAllProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) {
Assumptions.assumeTrue(!isHsmEnabled);
createKeyClient(httpClient, serviceVersion);
updateGetKeyRotationPolicyWithAllPropertiesRunner((keyName, keyRotationPolicy) -> {
client.createRsaKey(new CreateRsaKeyOptions(keyName));
KeyRotationPolicy updatedKeyRotationPolicy =
client.updateKeyRotationPolicy(keyName, keyRotationPolicy);
KeyRotationPolicy retrievedKeyRotationPolicy = client.getKeyRotationPolicy(keyName);
assertKeyVaultRotationPolicyEquals(updatedKeyRotationPolicy, retrievedKeyRotationPolicy);
});
}
/**
* Tests that a key can be rotated.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
@DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true")
public void rotateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
Assumptions.assumeTrue(!isHsmEnabled);
createKeyClient(httpClient, serviceVersion);
String keyName = testResourceNamer.randomName("rotateKey", 20);
KeyVaultKey createdKey = client.createRsaKey(new CreateRsaKeyOptions(keyName));
KeyVaultKey rotatedKey = client.rotateKey(keyName);
assertEquals(createdKey.getName(), rotatedKey.getName());
assertEquals(createdKey.getProperties().getTags(), rotatedKey.getProperties().getTags());
}
/**
* Tests that a {@link CryptographyClient} can be created for a given key and version using a {@link KeyClient}.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getCryptographyClient(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
CryptographyClient cryptographyClient = client.getCryptographyClient("myKey");
assertNotNull(cryptographyClient);
}
/**
* Tests that a {@link CryptographyClient} can be created for a given key using a {@link KeyClient}. Also tests
* that cryptographic operations can be performed with said cryptography client.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getCryptographyClientAndEncryptDecrypt(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
setKeyRunner((createKeyOptions) -> {
assertKeyEquals(createKeyOptions, client.createKey(createKeyOptions));
CryptographyClient cryptographyClient = client.getCryptographyClient(createKeyOptions.getName());
assertNotNull(cryptographyClient);
byte[] plaintext = "myPlaintext".getBytes();
byte[] ciphertext = cryptographyClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext).getCipherText();
byte[] decryptedText = cryptographyClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext).getPlainText();
assertArrayEquals(plaintext, decryptedText);
});
}
/**
* Tests that a {@link CryptographyClient} can be created for a given key and version using a {@link KeyClient}.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getCryptographyClientWithKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
CryptographyClient cryptographyClient =
client.getCryptographyClient("myKey", "6A385B124DEF4096AF1361A85B16C204");
assertNotNull(cryptographyClient);
}
/**
* Tests that a {@link CryptographyClient} can be created for a given key using a {@link KeyClient}.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getCryptographyClientWithEmptyKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
CryptographyClient cryptographyClient = client.getCryptographyClient("myKey", "");
assertNotNull(cryptographyClient);
}
/**
* Tests that a {@link CryptographyClient} can be created for a given key using a {@link KeyClient}.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getCryptographyClientWithNullKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
CryptographyClient cryptographyClient = client.getCryptographyClient("myKey", null);
assertNotNull(cryptographyClient);
}
private void pollOnKeyPurge(String keyName) {
int pendingPollCount = 0;
while (pendingPollCount < 10) {
DeletedKey deletedKey = null;
try {
deletedKey = client.getDeletedKey(keyName);
} catch (ResourceNotFoundException e) {
}
if (deletedKey != null) {
sleepInRecordMode(2000);
pendingPollCount += 1;
continue;
} else {
return;
}
}
System.err.printf("Deleted Key %s was not purged \n", keyName);
}
} |
I notice in tests, we are adding prefix `"vmId:"`, if that's the prefix we always want to add, worth adding it here? like we have done in `setMachineId()` ? | public void withMachineId(String machineId) {
this.machineId = machineId;
} | this.machineId = machineId; | public void withMachineId(String machineId) {
this.machineId = machineId;
} | class DiagnosticsClientConfig {
private AtomicInteger activeClientsCnt;
private int clientId;
private ConsistencyLevel consistencyLevel;
private boolean connectionSharingAcrossClientsEnabled;
private String consistencyRelatedConfigAsString;
private String httpConfigAsString;
private String otherCfgAsString;
private List<String> preferredRegions;
private boolean endpointDiscoveryEnabled;
private boolean multipleWriteRegionsEnabled;
private HttpClientConfig httpClientConfig;
private RntbdTransportClient.Options options;
private String rntbdConfigAsString;
private ConnectionMode connectionMode;
private String machineId;
public void withActiveClientCounter(AtomicInteger activeClientsCnt) {
this.activeClientsCnt = activeClientsCnt;
}
public void withClientId(int clientId) {
this.clientId = clientId;
}
public DiagnosticsClientConfig withEndpointDiscoveryEnabled(boolean endpointDiscoveryEnabled) {
this.endpointDiscoveryEnabled = endpointDiscoveryEnabled;
return this;
}
public DiagnosticsClientConfig withMultipleWriteRegionsEnabled(boolean multipleWriteRegionsEnabled) {
this.multipleWriteRegionsEnabled = multipleWriteRegionsEnabled;
return this;
}
public DiagnosticsClientConfig withPreferredRegions(List<String> preferredRegions) {
this.preferredRegions = preferredRegions;
return this;
}
public DiagnosticsClientConfig withConnectionSharingAcrossClientsEnabled(boolean connectionSharingAcrossClientsEnabled) {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
return this;
}
public DiagnosticsClientConfig withConsistency(ConsistencyLevel consistencyLevel) {
this.consistencyLevel = consistencyLevel;
return this;
}
public DiagnosticsClientConfig withRntbdOptions(RntbdTransportClient.Options options) {
this.options = options;
return this;
}
public DiagnosticsClientConfig withGatewayHttpClientConfig(HttpClientConfig httpClientConfig) {
this.httpClientConfig = httpClientConfig;
return this;
}
public DiagnosticsClientConfig withConnectionMode(ConnectionMode connectionMode) {
this.connectionMode = connectionMode;
return this;
}
public ConnectionMode getConnectionMode() {
return connectionMode;
}
public String consistencyRelatedConfig() {
if (consistencyRelatedConfigAsString == null) {
this.consistencyRelatedConfigAsString = this.consistencyRelatedConfigInternal();
}
return this.consistencyRelatedConfigAsString;
}
public String rntbdConfig() {
if (this.rntbdConfigAsString == null) {
this.rntbdConfigAsString = this.rntbdConfigInternal(this.options);
}
return this.rntbdConfigAsString;
}
public String gwConfig() {
if (this.httpConfigAsString == null) {
this.httpConfigAsString = this.gwConfigInternal();
}
return this.httpConfigAsString;
}
public String otherConnectionConfig() {
if (this.otherCfgAsString == null) {
this.otherCfgAsString = Strings.lenientFormat("(ed: %s, cs: %s)",
this.endpointDiscoveryEnabled,
this.connectionSharingAcrossClientsEnabled);
}
return this.otherCfgAsString;
}
public int getClientId() {
return this.clientId;
}
public String getMachineId() { return this.machineId; }
public int getActiveClientsCount() {
return this.activeClientsCnt != null ? this.activeClientsCnt.get() : -1;
}
private String gwConfigInternal() {
if (this.httpClientConfig == null) {
return null;
}
return Strings.lenientFormat("(cps:%s, nrto:%s, icto:%s, p:%s)",
this.httpClientConfig.getMaxPoolSize(),
this.httpClientConfig.getNetworkRequestTimeout(),
this.httpClientConfig.getMaxIdleConnectionTimeout(),
this.httpClientConfig.getProxy() != null);
}
private String rntbdConfigInternal(RntbdTransportClient.Options rntbdOptions) {
if (rntbdOptions == null) {
return null;
}
return Strings.lenientFormat("(cto:%s, nrto:%s, icto:%s, ieto:%s, mcpe:%s, mrpc:%s, cer:%s)",
rntbdOptions.connectTimeout(),
rntbdOptions.tcpNetworkRequestTimeout(),
rntbdOptions.idleChannelTimeout(),
rntbdOptions.idleEndpointTimeout(),
rntbdOptions.maxChannelsPerEndpoint(),
rntbdOptions.maxRequestsPerChannel(),
rntbdOptions.isConnectionEndpointRediscoveryEnabled());
}
private String preferredRegionsInternal() {
if (preferredRegions == null) {
return "";
}
return preferredRegions.stream().map(r -> r.toLowerCase(Locale.ROOT).replaceAll(" ", "")).collect(Collectors.joining(","));
}
private String consistencyRelatedConfigInternal() {
return Strings.lenientFormat("(consistency: %s, mm: %s, prgns: [%s])", this.consistencyLevel,
this.multipleWriteRegionsEnabled,
preferredRegionsInternal());
}
} | class DiagnosticsClientConfig {
private AtomicInteger activeClientsCnt;
private int clientId;
private ConsistencyLevel consistencyLevel;
private boolean connectionSharingAcrossClientsEnabled;
private String consistencyRelatedConfigAsString;
private String httpConfigAsString;
private String otherCfgAsString;
private List<String> preferredRegions;
private boolean endpointDiscoveryEnabled;
private boolean multipleWriteRegionsEnabled;
private HttpClientConfig httpClientConfig;
private RntbdTransportClient.Options options;
private String rntbdConfigAsString;
private ConnectionMode connectionMode;
private String machineId;
public void withActiveClientCounter(AtomicInteger activeClientsCnt) {
this.activeClientsCnt = activeClientsCnt;
}
public void withClientId(int clientId) {
this.clientId = clientId;
}
public DiagnosticsClientConfig withEndpointDiscoveryEnabled(boolean endpointDiscoveryEnabled) {
this.endpointDiscoveryEnabled = endpointDiscoveryEnabled;
return this;
}
public DiagnosticsClientConfig withMultipleWriteRegionsEnabled(boolean multipleWriteRegionsEnabled) {
this.multipleWriteRegionsEnabled = multipleWriteRegionsEnabled;
return this;
}
public DiagnosticsClientConfig withPreferredRegions(List<String> preferredRegions) {
this.preferredRegions = preferredRegions;
return this;
}
public DiagnosticsClientConfig withConnectionSharingAcrossClientsEnabled(boolean connectionSharingAcrossClientsEnabled) {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
return this;
}
public DiagnosticsClientConfig withConsistency(ConsistencyLevel consistencyLevel) {
this.consistencyLevel = consistencyLevel;
return this;
}
public DiagnosticsClientConfig withRntbdOptions(RntbdTransportClient.Options options) {
this.options = options;
return this;
}
public DiagnosticsClientConfig withGatewayHttpClientConfig(HttpClientConfig httpClientConfig) {
this.httpClientConfig = httpClientConfig;
return this;
}
public DiagnosticsClientConfig withConnectionMode(ConnectionMode connectionMode) {
this.connectionMode = connectionMode;
return this;
}
public ConnectionMode getConnectionMode() {
return connectionMode;
}
public String consistencyRelatedConfig() {
if (consistencyRelatedConfigAsString == null) {
this.consistencyRelatedConfigAsString = this.consistencyRelatedConfigInternal();
}
return this.consistencyRelatedConfigAsString;
}
public String rntbdConfig() {
if (this.rntbdConfigAsString == null) {
this.rntbdConfigAsString = this.rntbdConfigInternal(this.options);
}
return this.rntbdConfigAsString;
}
public String gwConfig() {
if (this.httpConfigAsString == null) {
this.httpConfigAsString = this.gwConfigInternal();
}
return this.httpConfigAsString;
}
public String otherConnectionConfig() {
if (this.otherCfgAsString == null) {
this.otherCfgAsString = Strings.lenientFormat("(ed: %s, cs: %s)",
this.endpointDiscoveryEnabled,
this.connectionSharingAcrossClientsEnabled);
}
return this.otherCfgAsString;
}
public int getClientId() {
return this.clientId;
}
public String getMachineId() { return this.machineId; }
public int getActiveClientsCount() {
return this.activeClientsCnt != null ? this.activeClientsCnt.get() : -1;
}
private String gwConfigInternal() {
if (this.httpClientConfig == null) {
return null;
}
return Strings.lenientFormat("(cps:%s, nrto:%s, icto:%s, p:%s)",
this.httpClientConfig.getMaxPoolSize(),
this.httpClientConfig.getNetworkRequestTimeout(),
this.httpClientConfig.getMaxIdleConnectionTimeout(),
this.httpClientConfig.getProxy() != null);
}
private String rntbdConfigInternal(RntbdTransportClient.Options rntbdOptions) {
if (rntbdOptions == null) {
return null;
}
return Strings.lenientFormat("(cto:%s, nrto:%s, icto:%s, ieto:%s, mcpe:%s, mrpc:%s, cer:%s)",
rntbdOptions.connectTimeout(),
rntbdOptions.tcpNetworkRequestTimeout(),
rntbdOptions.idleChannelTimeout(),
rntbdOptions.idleEndpointTimeout(),
rntbdOptions.maxChannelsPerEndpoint(),
rntbdOptions.maxRequestsPerChannel(),
rntbdOptions.isConnectionEndpointRediscoveryEnabled());
}
private String preferredRegionsInternal() {
if (preferredRegions == null) {
return "";
}
return preferredRegions.stream().map(r -> r.toLowerCase(Locale.ROOT).replaceAll(" ", "")).collect(Collectors.joining(","));
}
private String consistencyRelatedConfigInternal() {
return Strings.lenientFormat("(consistency: %s, mm: %s, prgns: [%s])", this.consistencyLevel,
this.multipleWriteRegionsEnabled,
preferredRegionsInternal());
}
} |
"vmId" would be used if the identifier comes from VM Instance metadata - uuid: prefix if it is the static identifier | public void withMachineId(String machineId) {
this.machineId = machineId;
} | this.machineId = machineId; | public void withMachineId(String machineId) {
this.machineId = machineId;
} | class DiagnosticsClientConfig {
private AtomicInteger activeClientsCnt;
private int clientId;
private ConsistencyLevel consistencyLevel;
private boolean connectionSharingAcrossClientsEnabled;
private String consistencyRelatedConfigAsString;
private String httpConfigAsString;
private String otherCfgAsString;
private List<String> preferredRegions;
private boolean endpointDiscoveryEnabled;
private boolean multipleWriteRegionsEnabled;
private HttpClientConfig httpClientConfig;
private RntbdTransportClient.Options options;
private String rntbdConfigAsString;
private ConnectionMode connectionMode;
private String machineId;
public void withActiveClientCounter(AtomicInteger activeClientsCnt) {
this.activeClientsCnt = activeClientsCnt;
}
public void withClientId(int clientId) {
this.clientId = clientId;
}
public DiagnosticsClientConfig withEndpointDiscoveryEnabled(boolean endpointDiscoveryEnabled) {
this.endpointDiscoveryEnabled = endpointDiscoveryEnabled;
return this;
}
public DiagnosticsClientConfig withMultipleWriteRegionsEnabled(boolean multipleWriteRegionsEnabled) {
this.multipleWriteRegionsEnabled = multipleWriteRegionsEnabled;
return this;
}
public DiagnosticsClientConfig withPreferredRegions(List<String> preferredRegions) {
this.preferredRegions = preferredRegions;
return this;
}
public DiagnosticsClientConfig withConnectionSharingAcrossClientsEnabled(boolean connectionSharingAcrossClientsEnabled) {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
return this;
}
public DiagnosticsClientConfig withConsistency(ConsistencyLevel consistencyLevel) {
this.consistencyLevel = consistencyLevel;
return this;
}
public DiagnosticsClientConfig withRntbdOptions(RntbdTransportClient.Options options) {
this.options = options;
return this;
}
public DiagnosticsClientConfig withGatewayHttpClientConfig(HttpClientConfig httpClientConfig) {
this.httpClientConfig = httpClientConfig;
return this;
}
public DiagnosticsClientConfig withConnectionMode(ConnectionMode connectionMode) {
this.connectionMode = connectionMode;
return this;
}
public ConnectionMode getConnectionMode() {
return connectionMode;
}
public String consistencyRelatedConfig() {
if (consistencyRelatedConfigAsString == null) {
this.consistencyRelatedConfigAsString = this.consistencyRelatedConfigInternal();
}
return this.consistencyRelatedConfigAsString;
}
public String rntbdConfig() {
if (this.rntbdConfigAsString == null) {
this.rntbdConfigAsString = this.rntbdConfigInternal(this.options);
}
return this.rntbdConfigAsString;
}
public String gwConfig() {
if (this.httpConfigAsString == null) {
this.httpConfigAsString = this.gwConfigInternal();
}
return this.httpConfigAsString;
}
public String otherConnectionConfig() {
if (this.otherCfgAsString == null) {
this.otherCfgAsString = Strings.lenientFormat("(ed: %s, cs: %s)",
this.endpointDiscoveryEnabled,
this.connectionSharingAcrossClientsEnabled);
}
return this.otherCfgAsString;
}
public int getClientId() {
return this.clientId;
}
public String getMachineId() { return this.machineId; }
public int getActiveClientsCount() {
return this.activeClientsCnt != null ? this.activeClientsCnt.get() : -1;
}
private String gwConfigInternal() {
if (this.httpClientConfig == null) {
return null;
}
return Strings.lenientFormat("(cps:%s, nrto:%s, icto:%s, p:%s)",
this.httpClientConfig.getMaxPoolSize(),
this.httpClientConfig.getNetworkRequestTimeout(),
this.httpClientConfig.getMaxIdleConnectionTimeout(),
this.httpClientConfig.getProxy() != null);
}
private String rntbdConfigInternal(RntbdTransportClient.Options rntbdOptions) {
if (rntbdOptions == null) {
return null;
}
return Strings.lenientFormat("(cto:%s, nrto:%s, icto:%s, ieto:%s, mcpe:%s, mrpc:%s, cer:%s)",
rntbdOptions.connectTimeout(),
rntbdOptions.tcpNetworkRequestTimeout(),
rntbdOptions.idleChannelTimeout(),
rntbdOptions.idleEndpointTimeout(),
rntbdOptions.maxChannelsPerEndpoint(),
rntbdOptions.maxRequestsPerChannel(),
rntbdOptions.isConnectionEndpointRediscoveryEnabled());
}
private String preferredRegionsInternal() {
if (preferredRegions == null) {
return "";
}
return preferredRegions.stream().map(r -> r.toLowerCase(Locale.ROOT).replaceAll(" ", "")).collect(Collectors.joining(","));
}
private String consistencyRelatedConfigInternal() {
return Strings.lenientFormat("(consistency: %s, mm: %s, prgns: [%s])", this.consistencyLevel,
this.multipleWriteRegionsEnabled,
preferredRegionsInternal());
}
} | class DiagnosticsClientConfig {
private AtomicInteger activeClientsCnt;
private int clientId;
private ConsistencyLevel consistencyLevel;
private boolean connectionSharingAcrossClientsEnabled;
private String consistencyRelatedConfigAsString;
private String httpConfigAsString;
private String otherCfgAsString;
private List<String> preferredRegions;
private boolean endpointDiscoveryEnabled;
private boolean multipleWriteRegionsEnabled;
private HttpClientConfig httpClientConfig;
private RntbdTransportClient.Options options;
private String rntbdConfigAsString;
private ConnectionMode connectionMode;
private String machineId;
public void withActiveClientCounter(AtomicInteger activeClientsCnt) {
this.activeClientsCnt = activeClientsCnt;
}
public void withClientId(int clientId) {
this.clientId = clientId;
}
public DiagnosticsClientConfig withEndpointDiscoveryEnabled(boolean endpointDiscoveryEnabled) {
this.endpointDiscoveryEnabled = endpointDiscoveryEnabled;
return this;
}
public DiagnosticsClientConfig withMultipleWriteRegionsEnabled(boolean multipleWriteRegionsEnabled) {
this.multipleWriteRegionsEnabled = multipleWriteRegionsEnabled;
return this;
}
public DiagnosticsClientConfig withPreferredRegions(List<String> preferredRegions) {
this.preferredRegions = preferredRegions;
return this;
}
public DiagnosticsClientConfig withConnectionSharingAcrossClientsEnabled(boolean connectionSharingAcrossClientsEnabled) {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
return this;
}
public DiagnosticsClientConfig withConsistency(ConsistencyLevel consistencyLevel) {
this.consistencyLevel = consistencyLevel;
return this;
}
public DiagnosticsClientConfig withRntbdOptions(RntbdTransportClient.Options options) {
this.options = options;
return this;
}
public DiagnosticsClientConfig withGatewayHttpClientConfig(HttpClientConfig httpClientConfig) {
this.httpClientConfig = httpClientConfig;
return this;
}
public DiagnosticsClientConfig withConnectionMode(ConnectionMode connectionMode) {
this.connectionMode = connectionMode;
return this;
}
public ConnectionMode getConnectionMode() {
return connectionMode;
}
public String consistencyRelatedConfig() {
if (consistencyRelatedConfigAsString == null) {
this.consistencyRelatedConfigAsString = this.consistencyRelatedConfigInternal();
}
return this.consistencyRelatedConfigAsString;
}
public String rntbdConfig() {
if (this.rntbdConfigAsString == null) {
this.rntbdConfigAsString = this.rntbdConfigInternal(this.options);
}
return this.rntbdConfigAsString;
}
public String gwConfig() {
if (this.httpConfigAsString == null) {
this.httpConfigAsString = this.gwConfigInternal();
}
return this.httpConfigAsString;
}
public String otherConnectionConfig() {
if (this.otherCfgAsString == null) {
this.otherCfgAsString = Strings.lenientFormat("(ed: %s, cs: %s)",
this.endpointDiscoveryEnabled,
this.connectionSharingAcrossClientsEnabled);
}
return this.otherCfgAsString;
}
public int getClientId() {
return this.clientId;
}
public String getMachineId() { return this.machineId; }
public int getActiveClientsCount() {
return this.activeClientsCnt != null ? this.activeClientsCnt.get() : -1;
}
private String gwConfigInternal() {
if (this.httpClientConfig == null) {
return null;
}
return Strings.lenientFormat("(cps:%s, nrto:%s, icto:%s, p:%s)",
this.httpClientConfig.getMaxPoolSize(),
this.httpClientConfig.getNetworkRequestTimeout(),
this.httpClientConfig.getMaxIdleConnectionTimeout(),
this.httpClientConfig.getProxy() != null);
}
private String rntbdConfigInternal(RntbdTransportClient.Options rntbdOptions) {
if (rntbdOptions == null) {
return null;
}
return Strings.lenientFormat("(cto:%s, nrto:%s, icto:%s, ieto:%s, mcpe:%s, mrpc:%s, cer:%s)",
rntbdOptions.connectTimeout(),
rntbdOptions.tcpNetworkRequestTimeout(),
rntbdOptions.idleChannelTimeout(),
rntbdOptions.idleEndpointTimeout(),
rntbdOptions.maxChannelsPerEndpoint(),
rntbdOptions.maxRequestsPerChannel(),
rntbdOptions.isConnectionEndpointRediscoveryEnabled());
}
private String preferredRegionsInternal() {
if (preferredRegions == null) {
return "";
}
return preferredRegions.stream().map(r -> r.toLowerCase(Locale.ROOT).replaceAll(" ", "")).collect(Collectors.joining(","));
}
private String consistencyRelatedConfigInternal() {
return Strings.lenientFormat("(consistency: %s, mm: %s, prgns: [%s])", this.consistencyLevel,
this.multipleWriteRegionsEnabled,
preferredRegionsInternal());
}
} |
Should we also rename the getter and the instance variable to `getVmId()` and `vmId` ? | public String getMachineId() {
return machineId;
} | return machineId; | public String getMachineId() {
return machineId;
} | class ClientTelemetryInfo {
private String timeStamp;
private String machineId;
private String clientId;
private String processId;
private String userAgent;
private ConnectionMode connectionMode;
private String globalDatabaseAccountName;
private String applicationRegion;
private String hostEnvInfo;
private Boolean acceleratedNetworking;
private int aggregationIntervalInSec;
private List<String> preferredRegions;
private Map<ReportPayload, ConcurrentDoubleHistogram> systemInfoMap;
private Map<ReportPayload, ConcurrentDoubleHistogram> cacheRefreshInfoMap;
private Map<ReportPayload, ConcurrentDoubleHistogram> operationInfoMap;
public ClientTelemetryInfo(String machineId,
String clientId,
String processId,
String userAgent,
ConnectionMode connectionMode,
String globalDatabaseAccountName,
String applicationRegion,
String hostEnvInfo,
Boolean acceleratedNetworking,
List<String> preferredRegions) {
this.machineId = machineId;
this.clientId = clientId;
this.processId = processId;
this.userAgent = userAgent;
this.connectionMode = connectionMode;
this.globalDatabaseAccountName = globalDatabaseAccountName;
this.applicationRegion = applicationRegion;
this.hostEnvInfo = hostEnvInfo;
this.acceleratedNetworking = acceleratedNetworking;
this.systemInfoMap = new ConcurrentHashMap<>();
this.cacheRefreshInfoMap = new ConcurrentHashMap<>();
this.operationInfoMap = new ConcurrentHashMap<>();
this.aggregationIntervalInSec = Configs.getClientTelemetrySchedulingInSec();
this.preferredRegions = preferredRegions;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getProcessId() {
return processId;
}
public void setProcessId(String processId) {
this.processId = processId;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public ConnectionMode getConnectionMode() {
return connectionMode;
}
public void setConnectionMode(ConnectionMode connectionMode) {
this.connectionMode = connectionMode;
}
public String getGlobalDatabaseAccountName() {
return globalDatabaseAccountName;
}
public void setGlobalDatabaseAccountName(String globalDatabaseAccountName) {
this.globalDatabaseAccountName = globalDatabaseAccountName;
}
public String getApplicationRegion() {
return applicationRegion;
}
public void setApplicationRegion(String applicationRegion) {
this.applicationRegion = applicationRegion;
}
public void setVmId(String vmId) {
this.machineId = "vmId:" + machineId;
}
public String getHostEnvInfo() {
return hostEnvInfo;
}
public void setHostEnvInfo(String hostEnvInfo) {
this.hostEnvInfo = hostEnvInfo;
}
public Boolean getAcceleratedNetworking() {
return acceleratedNetworking;
}
public void setAcceleratedNetworking(Boolean acceleratedNetworking) {
this.acceleratedNetworking = acceleratedNetworking;
}
public int getAggregationIntervalInSec() {
return aggregationIntervalInSec;
}
public void setAggregationIntervalInSec(int aggregationIntervalInSec) {
this.aggregationIntervalInSec = aggregationIntervalInSec;
}
public List<String> getPreferredRegions() {
return preferredRegions;
}
public void setPreferredRegions(List<String> preferredRegions) {
this.preferredRegions = preferredRegions;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getSystemInfoMap() {
return systemInfoMap;
}
public void setSystemInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> systemInfoMap) {
this.systemInfoMap = systemInfoMap;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getCacheRefreshInfoMap() {
return cacheRefreshInfoMap;
}
public void setCacheRefreshInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> cacheRefreshInfoMap) {
this.cacheRefreshInfoMap = cacheRefreshInfoMap;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getOperationInfoMap() {
return operationInfoMap;
}
public void setOperationInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> operationInfoMap) {
this.operationInfoMap = operationInfoMap;
}
} | class ClientTelemetryInfo {
private String timeStamp;
private String machineId;
private String clientId;
private String processId;
private String userAgent;
private ConnectionMode connectionMode;
private String globalDatabaseAccountName;
private String applicationRegion;
private String hostEnvInfo;
private Boolean acceleratedNetworking;
private int aggregationIntervalInSec;
private List<String> preferredRegions;
private Map<ReportPayload, ConcurrentDoubleHistogram> systemInfoMap;
private Map<ReportPayload, ConcurrentDoubleHistogram> cacheRefreshInfoMap;
private Map<ReportPayload, ConcurrentDoubleHistogram> operationInfoMap;
public ClientTelemetryInfo(String machineId,
String clientId,
String processId,
String userAgent,
ConnectionMode connectionMode,
String globalDatabaseAccountName,
String applicationRegion,
String hostEnvInfo,
Boolean acceleratedNetworking,
List<String> preferredRegions) {
this.machineId = machineId;
this.clientId = clientId;
this.processId = processId;
this.userAgent = userAgent;
this.connectionMode = connectionMode;
this.globalDatabaseAccountName = globalDatabaseAccountName;
this.applicationRegion = applicationRegion;
this.hostEnvInfo = hostEnvInfo;
this.acceleratedNetworking = acceleratedNetworking;
this.systemInfoMap = new ConcurrentHashMap<>();
this.cacheRefreshInfoMap = new ConcurrentHashMap<>();
this.operationInfoMap = new ConcurrentHashMap<>();
this.aggregationIntervalInSec = Configs.getClientTelemetrySchedulingInSec();
this.preferredRegions = preferredRegions;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getProcessId() {
return processId;
}
public void setProcessId(String processId) {
this.processId = processId;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public ConnectionMode getConnectionMode() {
return connectionMode;
}
public void setConnectionMode(ConnectionMode connectionMode) {
this.connectionMode = connectionMode;
}
public String getGlobalDatabaseAccountName() {
return globalDatabaseAccountName;
}
public void setGlobalDatabaseAccountName(String globalDatabaseAccountName) {
this.globalDatabaseAccountName = globalDatabaseAccountName;
}
public String getApplicationRegion() {
return applicationRegion;
}
public void setApplicationRegion(String applicationRegion) {
this.applicationRegion = applicationRegion;
}
public void setMachineId(String machineId) {
this.machineId = machineId;
}
public String getHostEnvInfo() {
return hostEnvInfo;
}
public void setHostEnvInfo(String hostEnvInfo) {
this.hostEnvInfo = hostEnvInfo;
}
public Boolean getAcceleratedNetworking() {
return acceleratedNetworking;
}
public void setAcceleratedNetworking(Boolean acceleratedNetworking) {
this.acceleratedNetworking = acceleratedNetworking;
}
public int getAggregationIntervalInSec() {
return aggregationIntervalInSec;
}
public void setAggregationIntervalInSec(int aggregationIntervalInSec) {
this.aggregationIntervalInSec = aggregationIntervalInSec;
}
public List<String> getPreferredRegions() {
return preferredRegions;
}
public void setPreferredRegions(List<String> preferredRegions) {
this.preferredRegions = preferredRegions;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getSystemInfoMap() {
return systemInfoMap;
}
public void setSystemInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> systemInfoMap) {
this.systemInfoMap = systemInfoMap;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getCacheRefreshInfoMap() {
return cacheRefreshInfoMap;
}
public void setCacheRefreshInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> cacheRefreshInfoMap) {
this.cacheRefreshInfoMap = cacheRefreshInfoMap;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getOperationInfoMap() {
return operationInfoMap;
}
public void setOperationInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> operationInfoMap) {
this.operationInfoMap = operationInfoMap;
}
} |
Not really - getMachineId will be used to get the prefixed-identifier. setVmId is currently only ever called in the callback when we retrieved the VM Instance metadata (a network call - to a loopback Uri only possible in Azure VMs) So, basically default is that we use the static UUID - if we are able to retrieve the VM instance metadata we override the machineId with the vmId (prefixed with "vmId:" so that we can distinguish it in request diagnostics. Similar mechanism to override (without necessary prefixing) is used for application region for example. | public String getMachineId() {
return machineId;
} | return machineId; | public String getMachineId() {
return machineId;
} | class ClientTelemetryInfo {
private String timeStamp;
private String machineId;
private String clientId;
private String processId;
private String userAgent;
private ConnectionMode connectionMode;
private String globalDatabaseAccountName;
private String applicationRegion;
private String hostEnvInfo;
private Boolean acceleratedNetworking;
private int aggregationIntervalInSec;
private List<String> preferredRegions;
private Map<ReportPayload, ConcurrentDoubleHistogram> systemInfoMap;
private Map<ReportPayload, ConcurrentDoubleHistogram> cacheRefreshInfoMap;
private Map<ReportPayload, ConcurrentDoubleHistogram> operationInfoMap;
public ClientTelemetryInfo(String machineId,
String clientId,
String processId,
String userAgent,
ConnectionMode connectionMode,
String globalDatabaseAccountName,
String applicationRegion,
String hostEnvInfo,
Boolean acceleratedNetworking,
List<String> preferredRegions) {
this.machineId = machineId;
this.clientId = clientId;
this.processId = processId;
this.userAgent = userAgent;
this.connectionMode = connectionMode;
this.globalDatabaseAccountName = globalDatabaseAccountName;
this.applicationRegion = applicationRegion;
this.hostEnvInfo = hostEnvInfo;
this.acceleratedNetworking = acceleratedNetworking;
this.systemInfoMap = new ConcurrentHashMap<>();
this.cacheRefreshInfoMap = new ConcurrentHashMap<>();
this.operationInfoMap = new ConcurrentHashMap<>();
this.aggregationIntervalInSec = Configs.getClientTelemetrySchedulingInSec();
this.preferredRegions = preferredRegions;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getProcessId() {
return processId;
}
public void setProcessId(String processId) {
this.processId = processId;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public ConnectionMode getConnectionMode() {
return connectionMode;
}
public void setConnectionMode(ConnectionMode connectionMode) {
this.connectionMode = connectionMode;
}
public String getGlobalDatabaseAccountName() {
return globalDatabaseAccountName;
}
public void setGlobalDatabaseAccountName(String globalDatabaseAccountName) {
this.globalDatabaseAccountName = globalDatabaseAccountName;
}
public String getApplicationRegion() {
return applicationRegion;
}
public void setApplicationRegion(String applicationRegion) {
this.applicationRegion = applicationRegion;
}
public void setVmId(String vmId) {
this.machineId = "vmId:" + machineId;
}
public String getHostEnvInfo() {
return hostEnvInfo;
}
public void setHostEnvInfo(String hostEnvInfo) {
this.hostEnvInfo = hostEnvInfo;
}
public Boolean getAcceleratedNetworking() {
return acceleratedNetworking;
}
public void setAcceleratedNetworking(Boolean acceleratedNetworking) {
this.acceleratedNetworking = acceleratedNetworking;
}
public int getAggregationIntervalInSec() {
return aggregationIntervalInSec;
}
public void setAggregationIntervalInSec(int aggregationIntervalInSec) {
this.aggregationIntervalInSec = aggregationIntervalInSec;
}
public List<String> getPreferredRegions() {
return preferredRegions;
}
public void setPreferredRegions(List<String> preferredRegions) {
this.preferredRegions = preferredRegions;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getSystemInfoMap() {
return systemInfoMap;
}
public void setSystemInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> systemInfoMap) {
this.systemInfoMap = systemInfoMap;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getCacheRefreshInfoMap() {
return cacheRefreshInfoMap;
}
public void setCacheRefreshInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> cacheRefreshInfoMap) {
this.cacheRefreshInfoMap = cacheRefreshInfoMap;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getOperationInfoMap() {
return operationInfoMap;
}
public void setOperationInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> operationInfoMap) {
this.operationInfoMap = operationInfoMap;
}
} | class ClientTelemetryInfo {
private String timeStamp;
private String machineId;
private String clientId;
private String processId;
private String userAgent;
private ConnectionMode connectionMode;
private String globalDatabaseAccountName;
private String applicationRegion;
private String hostEnvInfo;
private Boolean acceleratedNetworking;
private int aggregationIntervalInSec;
private List<String> preferredRegions;
private Map<ReportPayload, ConcurrentDoubleHistogram> systemInfoMap;
private Map<ReportPayload, ConcurrentDoubleHistogram> cacheRefreshInfoMap;
private Map<ReportPayload, ConcurrentDoubleHistogram> operationInfoMap;
public ClientTelemetryInfo(String machineId,
String clientId,
String processId,
String userAgent,
ConnectionMode connectionMode,
String globalDatabaseAccountName,
String applicationRegion,
String hostEnvInfo,
Boolean acceleratedNetworking,
List<String> preferredRegions) {
this.machineId = machineId;
this.clientId = clientId;
this.processId = processId;
this.userAgent = userAgent;
this.connectionMode = connectionMode;
this.globalDatabaseAccountName = globalDatabaseAccountName;
this.applicationRegion = applicationRegion;
this.hostEnvInfo = hostEnvInfo;
this.acceleratedNetworking = acceleratedNetworking;
this.systemInfoMap = new ConcurrentHashMap<>();
this.cacheRefreshInfoMap = new ConcurrentHashMap<>();
this.operationInfoMap = new ConcurrentHashMap<>();
this.aggregationIntervalInSec = Configs.getClientTelemetrySchedulingInSec();
this.preferredRegions = preferredRegions;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getProcessId() {
return processId;
}
public void setProcessId(String processId) {
this.processId = processId;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public ConnectionMode getConnectionMode() {
return connectionMode;
}
public void setConnectionMode(ConnectionMode connectionMode) {
this.connectionMode = connectionMode;
}
public String getGlobalDatabaseAccountName() {
return globalDatabaseAccountName;
}
public void setGlobalDatabaseAccountName(String globalDatabaseAccountName) {
this.globalDatabaseAccountName = globalDatabaseAccountName;
}
public String getApplicationRegion() {
return applicationRegion;
}
public void setApplicationRegion(String applicationRegion) {
this.applicationRegion = applicationRegion;
}
public void setMachineId(String machineId) {
this.machineId = machineId;
}
public String getHostEnvInfo() {
return hostEnvInfo;
}
public void setHostEnvInfo(String hostEnvInfo) {
this.hostEnvInfo = hostEnvInfo;
}
public Boolean getAcceleratedNetworking() {
return acceleratedNetworking;
}
public void setAcceleratedNetworking(Boolean acceleratedNetworking) {
this.acceleratedNetworking = acceleratedNetworking;
}
public int getAggregationIntervalInSec() {
return aggregationIntervalInSec;
}
public void setAggregationIntervalInSec(int aggregationIntervalInSec) {
this.aggregationIntervalInSec = aggregationIntervalInSec;
}
public List<String> getPreferredRegions() {
return preferredRegions;
}
public void setPreferredRegions(List<String> preferredRegions) {
this.preferredRegions = preferredRegions;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getSystemInfoMap() {
return systemInfoMap;
}
public void setSystemInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> systemInfoMap) {
this.systemInfoMap = systemInfoMap;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getCacheRefreshInfoMap() {
return cacheRefreshInfoMap;
}
public void setCacheRefreshInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> cacheRefreshInfoMap) {
this.cacheRefreshInfoMap = cacheRefreshInfoMap;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getOperationInfoMap() {
return operationInfoMap;
}
public void setOperationInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> operationInfoMap) {
this.operationInfoMap = operationInfoMap;
}
} |
Got it, makes sense! | public String getMachineId() {
return machineId;
} | return machineId; | public String getMachineId() {
return machineId;
} | class ClientTelemetryInfo {
private String timeStamp;
private String machineId;
private String clientId;
private String processId;
private String userAgent;
private ConnectionMode connectionMode;
private String globalDatabaseAccountName;
private String applicationRegion;
private String hostEnvInfo;
private Boolean acceleratedNetworking;
private int aggregationIntervalInSec;
private List<String> preferredRegions;
private Map<ReportPayload, ConcurrentDoubleHistogram> systemInfoMap;
private Map<ReportPayload, ConcurrentDoubleHistogram> cacheRefreshInfoMap;
private Map<ReportPayload, ConcurrentDoubleHistogram> operationInfoMap;
public ClientTelemetryInfo(String machineId,
String clientId,
String processId,
String userAgent,
ConnectionMode connectionMode,
String globalDatabaseAccountName,
String applicationRegion,
String hostEnvInfo,
Boolean acceleratedNetworking,
List<String> preferredRegions) {
this.machineId = machineId;
this.clientId = clientId;
this.processId = processId;
this.userAgent = userAgent;
this.connectionMode = connectionMode;
this.globalDatabaseAccountName = globalDatabaseAccountName;
this.applicationRegion = applicationRegion;
this.hostEnvInfo = hostEnvInfo;
this.acceleratedNetworking = acceleratedNetworking;
this.systemInfoMap = new ConcurrentHashMap<>();
this.cacheRefreshInfoMap = new ConcurrentHashMap<>();
this.operationInfoMap = new ConcurrentHashMap<>();
this.aggregationIntervalInSec = Configs.getClientTelemetrySchedulingInSec();
this.preferredRegions = preferredRegions;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getProcessId() {
return processId;
}
public void setProcessId(String processId) {
this.processId = processId;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public ConnectionMode getConnectionMode() {
return connectionMode;
}
public void setConnectionMode(ConnectionMode connectionMode) {
this.connectionMode = connectionMode;
}
public String getGlobalDatabaseAccountName() {
return globalDatabaseAccountName;
}
public void setGlobalDatabaseAccountName(String globalDatabaseAccountName) {
this.globalDatabaseAccountName = globalDatabaseAccountName;
}
public String getApplicationRegion() {
return applicationRegion;
}
public void setApplicationRegion(String applicationRegion) {
this.applicationRegion = applicationRegion;
}
public void setVmId(String vmId) {
this.machineId = "vmId:" + machineId;
}
public String getHostEnvInfo() {
return hostEnvInfo;
}
public void setHostEnvInfo(String hostEnvInfo) {
this.hostEnvInfo = hostEnvInfo;
}
public Boolean getAcceleratedNetworking() {
return acceleratedNetworking;
}
public void setAcceleratedNetworking(Boolean acceleratedNetworking) {
this.acceleratedNetworking = acceleratedNetworking;
}
public int getAggregationIntervalInSec() {
return aggregationIntervalInSec;
}
public void setAggregationIntervalInSec(int aggregationIntervalInSec) {
this.aggregationIntervalInSec = aggregationIntervalInSec;
}
public List<String> getPreferredRegions() {
return preferredRegions;
}
public void setPreferredRegions(List<String> preferredRegions) {
this.preferredRegions = preferredRegions;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getSystemInfoMap() {
return systemInfoMap;
}
public void setSystemInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> systemInfoMap) {
this.systemInfoMap = systemInfoMap;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getCacheRefreshInfoMap() {
return cacheRefreshInfoMap;
}
public void setCacheRefreshInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> cacheRefreshInfoMap) {
this.cacheRefreshInfoMap = cacheRefreshInfoMap;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getOperationInfoMap() {
return operationInfoMap;
}
public void setOperationInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> operationInfoMap) {
this.operationInfoMap = operationInfoMap;
}
} | class ClientTelemetryInfo {
private String timeStamp;
private String machineId;
private String clientId;
private String processId;
private String userAgent;
private ConnectionMode connectionMode;
private String globalDatabaseAccountName;
private String applicationRegion;
private String hostEnvInfo;
private Boolean acceleratedNetworking;
private int aggregationIntervalInSec;
private List<String> preferredRegions;
private Map<ReportPayload, ConcurrentDoubleHistogram> systemInfoMap;
private Map<ReportPayload, ConcurrentDoubleHistogram> cacheRefreshInfoMap;
private Map<ReportPayload, ConcurrentDoubleHistogram> operationInfoMap;
public ClientTelemetryInfo(String machineId,
String clientId,
String processId,
String userAgent,
ConnectionMode connectionMode,
String globalDatabaseAccountName,
String applicationRegion,
String hostEnvInfo,
Boolean acceleratedNetworking,
List<String> preferredRegions) {
this.machineId = machineId;
this.clientId = clientId;
this.processId = processId;
this.userAgent = userAgent;
this.connectionMode = connectionMode;
this.globalDatabaseAccountName = globalDatabaseAccountName;
this.applicationRegion = applicationRegion;
this.hostEnvInfo = hostEnvInfo;
this.acceleratedNetworking = acceleratedNetworking;
this.systemInfoMap = new ConcurrentHashMap<>();
this.cacheRefreshInfoMap = new ConcurrentHashMap<>();
this.operationInfoMap = new ConcurrentHashMap<>();
this.aggregationIntervalInSec = Configs.getClientTelemetrySchedulingInSec();
this.preferredRegions = preferredRegions;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getProcessId() {
return processId;
}
public void setProcessId(String processId) {
this.processId = processId;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public ConnectionMode getConnectionMode() {
return connectionMode;
}
public void setConnectionMode(ConnectionMode connectionMode) {
this.connectionMode = connectionMode;
}
public String getGlobalDatabaseAccountName() {
return globalDatabaseAccountName;
}
public void setGlobalDatabaseAccountName(String globalDatabaseAccountName) {
this.globalDatabaseAccountName = globalDatabaseAccountName;
}
public String getApplicationRegion() {
return applicationRegion;
}
public void setApplicationRegion(String applicationRegion) {
this.applicationRegion = applicationRegion;
}
public void setMachineId(String machineId) {
this.machineId = machineId;
}
public String getHostEnvInfo() {
return hostEnvInfo;
}
public void setHostEnvInfo(String hostEnvInfo) {
this.hostEnvInfo = hostEnvInfo;
}
public Boolean getAcceleratedNetworking() {
return acceleratedNetworking;
}
public void setAcceleratedNetworking(Boolean acceleratedNetworking) {
this.acceleratedNetworking = acceleratedNetworking;
}
public int getAggregationIntervalInSec() {
return aggregationIntervalInSec;
}
public void setAggregationIntervalInSec(int aggregationIntervalInSec) {
this.aggregationIntervalInSec = aggregationIntervalInSec;
}
public List<String> getPreferredRegions() {
return preferredRegions;
}
public void setPreferredRegions(List<String> preferredRegions) {
this.preferredRegions = preferredRegions;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getSystemInfoMap() {
return systemInfoMap;
}
public void setSystemInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> systemInfoMap) {
this.systemInfoMap = systemInfoMap;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getCacheRefreshInfoMap() {
return cacheRefreshInfoMap;
}
public void setCacheRefreshInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> cacheRefreshInfoMap) {
this.cacheRefreshInfoMap = cacheRefreshInfoMap;
}
public Map<ReportPayload, ConcurrentDoubleHistogram> getOperationInfoMap() {
return operationInfoMap;
}
public void setOperationInfoMap(Map<ReportPayload, ConcurrentDoubleHistogram> operationInfoMap) {
this.operationInfoMap = operationInfoMap;
}
} |
Not related to this change, but since you are here, can we also update the clientId? Currently, it is this.clientId = clientIdGenerator.getAndDecrement() ----> can we change to getAndIncrement() (><) | public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) {
try {
this.httpClientInterceptor = httpClientInterceptor;
if (httpClientInterceptor != null) {
this.reactorHttpClient = httpClientInterceptor.apply(httpClient());
}
this.gatewayProxy = createRxGatewayProxy(this.sessionContainer,
this.consistencyLevel,
this.queryCompatibilityMode,
this.userAgentContainer,
this.globalEndpointManager,
this.reactorHttpClient,
this.apiType);
this.globalEndpointManager.init();
this.initializeGatewayConfigurationReader();
if (metadataCachesSnapshot != null) {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy,
metadataCachesSnapshot.getCollectionInfoByNameCache(),
metadataCachesSnapshot.getCollectionInfoByIdCache()
);
} else {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy);
}
this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy);
this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this,
collectionCache);
updateGatewayProxy();
clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(),
ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(),
connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(),
null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions());
clientTelemetry.init();
if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) {
this.storeModel = this.gatewayProxy;
} else {
this.initializeDirectConnectivity();
}
this.retryPolicy.setRxCollectionCache(this.collectionCache);
} catch (Exception e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
} | clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(), | public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) {
try {
this.httpClientInterceptor = httpClientInterceptor;
if (httpClientInterceptor != null) {
this.reactorHttpClient = httpClientInterceptor.apply(httpClient());
}
this.gatewayProxy = createRxGatewayProxy(this.sessionContainer,
this.consistencyLevel,
this.queryCompatibilityMode,
this.userAgentContainer,
this.globalEndpointManager,
this.reactorHttpClient,
this.apiType);
this.globalEndpointManager.init();
this.initializeGatewayConfigurationReader();
if (metadataCachesSnapshot != null) {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy,
metadataCachesSnapshot.getCollectionInfoByNameCache(),
metadataCachesSnapshot.getCollectionInfoByIdCache()
);
} else {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy);
}
this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy);
this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this,
collectionCache);
updateGatewayProxy();
clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(),
ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(),
connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(),
null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions());
clientTelemetry.init();
if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) {
this.storeModel = this.gatewayProxy;
} else {
this.initializeDirectConnectivity();
}
this.retryPolicy.setRxCollectionCache(this.collectionCache);
} catch (Exception e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
} | class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener,
DiagnosticsClientContext {
private static final String tempMachineId = "uuid:" + UUID.randomUUID();
private static final AtomicInteger activeClientsCnt = new AtomicInteger(0);
private static final AtomicInteger clientIdGenerator = new AtomicInteger(0);
private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>(
PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey,
PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false);
private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " +
"ParallelDocumentQueryExecutioncontext, but not used";
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper();
private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer();
private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class);
private final String masterKeyOrResourceToken;
private final URI serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel consistencyLevel;
private final BaseAuthorizationTokenProvider authorizationTokenProvider;
private final UserAgentContainer userAgentContainer;
private final boolean hasAuthKeyResourceToken;
private final Configs configs;
private final boolean connectionSharingAcrossClientsEnabled;
private AzureKeyCredential credential;
private final TokenCredential tokenCredential;
private String[] tokenCredentialScopes;
private SimpleTokenCache tokenCredentialCache;
private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver;
AuthorizationTokenType authorizationTokenType;
private SessionContainer sessionContainer;
private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY;
private RxClientCollectionCache collectionCache;
private RxStoreModel gatewayProxy;
private RxStoreModel storeModel;
private GlobalAddressResolver addressResolver;
private RxPartitionKeyRangeCache partitionKeyRangeCache;
private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap;
private final boolean contentResponseOnWriteEnabled;
private Map<String, PartitionedQueryExecutionInfo> queryPlanCache;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final int clientId;
private ClientTelemetry clientTelemetry;
private ApiType apiType;
private IRetryPolicyFactory resetSessionTokenRetryPolicy;
/**
* Compatibility mode: Allows to specify compatibility mode used by client when
* making query requests. Should be removed when application/sql is no longer
* supported.
*/
private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default;
private final GlobalEndpointManager globalEndpointManager;
private final RetryPolicy retryPolicy;
private HttpClient reactorHttpClient;
private Function<HttpClient, HttpClient> httpClientInterceptor;
private volatile boolean useMultipleWriteLocations;
private StoreClientFactory storeClientFactory;
private GatewayServiceConfigurationReader gatewayConfigurationReader;
private final DiagnosticsClientConfig diagnosticsClientConfig;
private final AtomicBoolean throughputControlEnabled;
private ThroughputControlStore throughputControlStore;
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
private RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
if (permissionFeed != null && permissionFeed.size() > 0) {
this.resourceTokensMap = new HashMap<>();
for (Permission permission : permissionFeed) {
String[] segments = StringUtils.split(permission.getResourceLink(),
Constants.Properties.PATH_SEPARATOR.charAt(0));
if (segments.length <= 0) {
throw new IllegalArgumentException("resourceLink");
}
List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null;
PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false);
if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) {
throw new IllegalArgumentException(permission.getResourceLink());
}
partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName);
if (partitionKeyAndResourceTokenPairs == null) {
partitionKeyAndResourceTokenPairs = new ArrayList<>();
this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs);
}
PartitionKey partitionKey = permission.getResourcePartitionKey();
partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair(
partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty,
permission.getToken()));
logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]",
pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken());
}
if(this.resourceTokensMap.isEmpty()) {
throw new IllegalArgumentException("permissionFeed");
}
String firstToken = permissionFeed.get(0).getToken();
if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) {
this.firstResourceTokenFromPermissionFeed = firstToken;
}
}
}
RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
activeClientsCnt.incrementAndGet();
this.clientId = clientIdGenerator.getAndDecrement();
this.diagnosticsClientConfig = new DiagnosticsClientConfig();
this.diagnosticsClientConfig.withClientId(this.clientId);
this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt);
this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled);
this.diagnosticsClientConfig.withConsistency(consistencyLevel);
this.throughputControlEnabled = new AtomicBoolean(false);
logger.info(
"Initializing DocumentClient [{}] with"
+ " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]",
this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol());
try {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
this.configs = configs;
this.masterKeyOrResourceToken = masterKeyOrResourceToken;
this.serviceEndpoint = serviceEndpoint;
this.credential = credential;
this.tokenCredential = tokenCredential;
this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled;
this.authorizationTokenType = AuthorizationTokenType.Invalid;
if (this.credential != null) {
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.authorizationTokenProvider = null;
hasAuthKeyResourceToken = true;
this.authorizationTokenType = AuthorizationTokenType.ResourceToken;
} else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken);
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else {
hasAuthKeyResourceToken = false;
this.authorizationTokenProvider = null;
if (tokenCredential != null) {
this.tokenCredentialScopes = new String[] {
serviceEndpoint.getScheme() + ":
};
this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential
.getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes)));
this.authorizationTokenType = AuthorizationTokenType.AadToken;
}
}
if (connectionPolicy != null) {
this.connectionPolicy = connectionPolicy;
} else {
this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig());
}
this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode());
this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled());
this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled());
this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions());
this.diagnosticsClientConfig.withMachineId(tempMachineId);
boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled);
this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing);
this.consistencyLevel = consistencyLevel;
this.userAgentContainer = new UserAgentContainer();
String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix();
if (userAgentSuffix != null && userAgentSuffix.length() > 0) {
userAgentContainer.setSuffix(userAgentSuffix);
}
this.httpClientInterceptor = null;
this.reactorHttpClient = httpClient();
this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs);
this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy);
this.resetSessionTokenRetryPolicy = retryPolicy;
CpuMemoryMonitor.register(this);
this.queryPlanCache = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE));
this.apiType = apiType;
} catch (RuntimeException e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
}
@Override
public DiagnosticsClientConfig getConfig() {
return diagnosticsClientConfig;
}
@Override
public CosmosDiagnostics createDiagnostics() {
return BridgeInternal.createCosmosDiagnostics(this, this.globalEndpointManager);
}
private void initializeGatewayConfigurationReader() {
this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager);
DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount();
if (databaseAccount == null) {
logger.error("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
throw new RuntimeException("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
}
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount);
}
private void updateGatewayProxy() {
((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader);
((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache);
((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache);
((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations);
}
public void serialize(CosmosClientMetadataCachesSnapshot state) {
RxCollectionCache.serialize(state, this.collectionCache);
}
private void initializeDirectConnectivity() {
this.addressResolver = new GlobalAddressResolver(this,
this.reactorHttpClient,
this.globalEndpointManager,
this.configs.getProtocol(),
this,
this.collectionCache,
this.partitionKeyRangeCache,
userAgentContainer,
null,
this.connectionPolicy,
this.apiType);
this.storeClientFactory = new StoreClientFactory(
this.addressResolver,
this.diagnosticsClientConfig,
this.configs,
this.connectionPolicy,
this.userAgentContainer,
this.connectionSharingAcrossClientsEnabled,
this.clientTelemetry
);
this.createStoreModel(true);
}
DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() {
return new DatabaseAccountManagerInternal() {
@Override
public URI getServiceEndpoint() {
return RxDocumentClientImpl.this.getServiceEndpoint();
}
@Override
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
logger.info("Getting database account endpoint from {}", endpoint);
return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return RxDocumentClientImpl.this.getConnectionPolicy();
}
};
}
RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer,
ConsistencyLevel consistencyLevel,
QueryCompatibilityMode queryCompatibilityMode,
UserAgentContainer userAgentContainer,
GlobalEndpointManager globalEndpointManager,
HttpClient httpClient,
ApiType apiType) {
return new RxGatewayStoreModel(
this,
sessionContainer,
consistencyLevel,
queryCompatibilityMode,
userAgentContainer,
globalEndpointManager,
httpClient,
apiType);
}
private HttpClient httpClient() {
HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs)
.withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout())
.withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize())
.withProxy(this.connectionPolicy.getProxy())
.withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout());
if (connectionSharingAcrossClientsEnabled) {
return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig);
} else {
diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig);
return HttpClient.createFixed(httpClientConfig);
}
}
private void createStoreModel(boolean subscribeRntbdStatus) {
StoreClient storeClient = this.storeClientFactory.createStoreClient(this,
this.addressResolver,
this.sessionContainer,
this.gatewayConfigurationReader,
this,
this.useMultipleWriteLocations
);
this.storeModel = new ServerStoreModel(storeClient);
}
@Override
public URI getServiceEndpoint() {
return this.serviceEndpoint;
}
@Override
public URI getWriteEndpoint() {
return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null);
}
@Override
public URI getReadEndpoint() {
return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return this.connectionPolicy;
}
@Override
public boolean isContentResponseOnWriteEnabled() {
return contentResponseOnWriteEnabled;
}
@Override
public ConsistencyLevel getConsistencyLevel() {
return consistencyLevel;
}
@Override
public ClientTelemetry getClientTelemetry() {
return this.clientTelemetry;
}
@Override
public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (database == null) {
throw new IllegalArgumentException("Database");
}
logger.debug("Creating a Database. id: [{}]", database.getId());
validateResource(database);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Reading a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT);
}
private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) {
switch (resourceTypeEnum) {
case Database:
return Paths.DATABASES_ROOT;
case DocumentCollection:
return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT);
case Document:
return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT);
case Offer:
return Paths.OFFERS_ROOT;
case User:
return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT);
case ClientEncryptionKey:
return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
case Permission:
return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT);
case Attachment:
return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT);
case StoredProcedure:
return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
case Trigger:
return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT);
case UserDefinedFunction:
return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
case Conflict:
return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT);
default:
throw new IllegalArgumentException("resource type not supported");
}
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) {
if (options == null) {
return null;
}
return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options);
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) {
if (options == null) {
return null;
}
return options.getOperationContextAndListenerTuple();
}
private <T extends Resource> Flux<FeedResponse<T>> createQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum) {
String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum);
UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getCorrelationActivityId(options);
UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ?
correlationActivityIdOfRequestOptions : Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this,
getOperationContextAndListenerTuple(options));
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> createQueryInternal(
resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId),
invalidPartitionExceptionRetryPolicy);
}
private <T extends Resource> Flux<FeedResponse<T>> createQueryInternal(
String resourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
IDocumentQueryClient queryClient,
UUID activityId) {
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory
.createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery,
options, resourceLink, false, activityId,
Configs.isQueryPlanCachingEnabled(), queryPlanCache);
AtomicBoolean isFirstResponse = new AtomicBoolean(true);
return executionContext.flatMap(iDocumentQueryExecutionContext -> {
QueryInfo queryInfo = null;
if (iDocumentQueryExecutionContext instanceof PipelinedDocumentQueryExecutionContext) {
queryInfo = ((PipelinedDocumentQueryExecutionContext<T>) iDocumentQueryExecutionContext).getQueryInfo();
}
QueryInfo finalQueryInfo = queryInfo;
return iDocumentQueryExecutionContext.executeAsync()
.map(tFeedResponse -> {
if (finalQueryInfo != null) {
if (finalQueryInfo.hasSelectValue()) {
ModelBridgeInternal
.addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo);
}
if (isFirstResponse.compareAndSet(true, false)) {
ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse,
finalQueryInfo.getQueryPlanDiagnosticsContext());
}
}
return tFeedResponse;
});
});
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) {
return queryDatabases(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database);
}
@Override
public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink,
DocumentCollection collection, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink,
DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink,
collection.getId());
validateResource(collection);
String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
});
} catch (Exception e) {
logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Replacing a Collection. id: [{}]", collection.getId());
validateResource(collection);
String path = Utils.joinPath(collection.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
if (resourceResponse.getResource() != null) {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
}
});
} catch (Exception e) {
logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.DELETE)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated));
}
private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated ->
this.getStoreProxy(requestPopulated).processMessage(requestPopulated)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
));
}
@Override
public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class,
Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection);
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection);
}
private static String serializeProcedureParams(List<Object> objectArray) {
String[] stringArray = new String[objectArray.size()];
for (int i = 0; i < objectArray.size(); ++i) {
Object object = objectArray.get(i);
if (object instanceof JsonSerializable) {
stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object);
} else {
try {
stringArray[i] = mapper.writeValueAsString(object);
} catch (IOException e) {
throw new IllegalArgumentException("Can't serialize the object into the json string", e);
}
}
}
return String.format("[%s]", StringUtils.join(stringArray, ","));
}
private static void validateResource(Resource resource) {
if (!StringUtils.isEmpty(resource.getId())) {
if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 ||
resource.getId().indexOf('?') != -1 || resource.getId().indexOf('
throw new IllegalArgumentException("Id contains illegal chars.");
}
if (resource.getId().endsWith(" ")) {
throw new IllegalArgumentException("Id ends with a space.");
}
}
}
private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) {
Map<String, String> headers = new HashMap<>();
if (this.useMultipleWriteLocations) {
headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString());
}
if (consistencyLevel != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString());
}
if (options == null) {
if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
return headers;
}
Map<String, String> customOptions = options.getHeaders();
if (customOptions != null) {
headers.putAll(customOptions);
}
boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled;
if (options.isContentResponseOnWriteEnabled() != null) {
contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled();
}
if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
if (options.getIfMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag());
}
if(options.getIfNoneMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag());
}
if (options.getConsistencyLevel() != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString());
}
if (options.getIndexingDirective() != null) {
headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString());
}
if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) {
String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude);
}
if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) {
String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude);
}
if (!Strings.isNullOrEmpty(options.getSessionToken())) {
headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken());
}
if (options.getResourceTokenExpirySeconds() != null) {
headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY,
String.valueOf(options.getResourceTokenExpirySeconds()));
}
if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString());
} else if (options.getOfferType() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType());
}
if (options.getOfferThroughput() == null) {
if (options.getThroughputProperties() != null) {
Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties());
final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings();
OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null;
if (offerAutoscaleSettings != null) {
autoscaleAutoUpgradeProperties
= offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties();
}
if (offer.hasOfferThroughput() &&
(offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 ||
autoscaleAutoUpgradeProperties != null &&
autoscaleAutoUpgradeProperties
.getAutoscaleThroughputProperties()
.getIncrementPercent() >= 0)) {
throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with "
+ "fixed offer");
}
if (offer.hasOfferThroughput()) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput()));
} else if (offer.getOfferAutoScaleSettings() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS,
ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings()));
}
}
}
if (options.isQuotaInfoEnabled()) {
headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true));
}
if (options.isScriptLoggingEnabled()) {
headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true));
}
if (options.getDedicatedGatewayRequestOptions() != null &&
options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) {
headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS,
String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions())));
}
return headers;
}
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return this.resetSessionTokenRetryPolicy;
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Document document,
RequestOptions options) {
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs
.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object document,
RequestOptions options,
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) {
return collectionObs.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private void addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object objectDoc, RequestOptions options,
DocumentCollection collection) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
PartitionKeyInternal partitionKeyInternal = null;
if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else if (options != null && options.getPartitionKey() != null) {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey());
} else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) {
partitionKeyInternal = PartitionKeyInternal.getEmpty();
} else if (contentAsByteBuffer != null || objectDoc != null) {
InternalObjectNode internalObjectNode;
if (objectDoc instanceof InternalObjectNode) {
internalObjectNode = (InternalObjectNode) objectDoc;
} else if (objectDoc instanceof ObjectNode) {
internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc);
} else if (contentAsByteBuffer != null) {
contentAsByteBuffer.rewind();
internalObjectNode = new InternalObjectNode(contentAsByteBuffer);
} else {
throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null");
}
Instant serializationStartTime = Instant.now();
partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTime,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION
);
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
} else {
throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation.");
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
}
public static PartitionKeyInternal extractPartitionKeyValueFromDocument(
InternalObjectNode document,
PartitionKeyDefinition partitionKeyDefinition) {
if (partitionKeyDefinition != null) {
switch (partitionKeyDefinition.getKind()) {
case HASH:
String path = partitionKeyDefinition.getPaths().iterator().next();
List<String> parts = PathParser.getPathParts(path);
if (parts.size() >= 1) {
Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts);
if (value == null || value.getClass() == ObjectNode.class) {
value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
}
if (value instanceof PartitionKeyInternal) {
return (PartitionKeyInternal) value;
} else {
return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false);
}
}
break;
case MULTI_HASH:
Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()];
for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){
String partitionPath = partitionKeyDefinition.getPaths().get(pathIter);
List<String> partitionPathParts = PathParser.getPathParts(partitionPath);
partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts);
}
return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false);
default:
throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind());
}
}
return null;
}
private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
Object document,
RequestOptions options,
boolean disableAutomaticIdGeneration,
OperationType operationType) {
if (StringUtils.isEmpty(documentCollectionLink)) {
throw new IllegalArgumentException("documentCollectionLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Document, path, requestHeaders, options, content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return addPartitionKeyInformation(request, content, document, options, collectionObs);
}
private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink");
checkNotNull(serverBatchRequest, "expected non null serverBatchRequest");
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody()));
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Batch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> {
addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v);
return request;
});
}
private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request,
ServerBatchRequest serverBatchRequest,
DocumentCollection collection) {
if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) {
PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue();
PartitionKeyInternal partitionKeyInternal;
if (partitionKey.equals(PartitionKey.NONE)) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey);
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
} else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) {
request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId()));
} else {
throw new UnsupportedOperationException("Unknown Server request.");
}
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString());
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch()));
request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError()));
request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size());
return request;
}
private Mono<RxDocumentServiceRequest> populateHeaders(RxDocumentServiceRequest request, RequestVerb httpMethod) {
request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123());
if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null
|| this.cosmosAuthorizationTokenResolver != null || this.credential != null) {
String resourceName = request.getResourceAddress();
String authorization = this.getUserAuthorizationToken(
resourceName, request.getResourceType(), httpMethod, request.getHeaders(),
AuthorizationTokenType.PrimaryMasterKey, request.properties);
try {
authorization = URLEncoder.encode(authorization, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Failed to encode authtoken.", e);
}
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
}
if (this.apiType != null) {
request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString());
}
if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod))
&& !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
}
if (RequestVerb.PATCH.equals(httpMethod) &&
!request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH);
}
if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) {
request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
}
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
if (this.requiresFeedRangeFiltering(request)) {
return request.getFeedRange()
.populateFeedRangeFilteringHeaders(
this.getPartitionKeyRangeCache(),
request,
this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request))
.flatMap(this::populateAuthorizationHeader);
}
return this.populateAuthorizationHeader(request);
}
private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) {
if (request.getResourceType() != ResourceType.Document &&
request.getResourceType() != ResourceType.Conflict) {
return false;
}
switch (request.getOperationType()) {
case ReadFeed:
case Query:
case SqlQuery:
return request.getFeedRange() != null;
default:
return false;
}
}
@Override
public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) {
if (request == null) {
throw new IllegalArgumentException("request");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return request;
});
} else {
return Mono.just(request);
}
}
@Override
public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) {
if (httpHeaders == null) {
throw new IllegalArgumentException("httpHeaders");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return httpHeaders;
});
}
return Mono.just(httpHeaders);
}
@Override
public AuthorizationTokenType getAuthorizationTokenType() {
return this.authorizationTokenType;
}
@Override
public String getUserAuthorizationToken(String resourceName,
ResourceType resourceType,
RequestVerb requestVerb,
Map<String, String> headers,
AuthorizationTokenType tokenType,
Map<String, Object> properties) {
if (this.cosmosAuthorizationTokenResolver != null) {
return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(),
properties != null ? Collections.unmodifiableMap(properties) : null);
} else if (credential != null) {
return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName,
resourceType, headers);
} else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) {
return masterKeyOrResourceToken;
} else {
assert resourceTokensMap != null;
if(resourceType.equals(ResourceType.DatabaseAccount)) {
return this.firstResourceTokenFromPermissionFeed;
}
return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers);
}
}
private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) {
CosmosResourceType cosmosResourceType =
ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString());
if (cosmosResourceType == null) {
return CosmosResourceType.SYSTEM;
}
return cosmosResourceType;
}
void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) {
this.sessionContainer.setSessionToken(request, response.getResponseHeaders());
}
private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
Map<String, String> headers = requestPopulated.getHeaders();
assert (headers != null);
headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true");
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
);
});
}
private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.PUT)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PATCH);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(request).processMessage(request);
}
@Override
public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) {
try {
logger.debug("Creating a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Create);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance);
}
private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Upsert);
Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = Utils.getCollectionName(documentLink);
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Document typedDocument = documentFromObject(document, mapper);
return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = document.getSelfLink();
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (document == null) {
throw new IllegalArgumentException("document");
}
return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a database due to [{}]", e.getMessage());
return Mono.error(e);
}
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink,
Document document,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
if (document == null) {
throw new IllegalArgumentException("document");
}
logger.debug("Replacing a Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = serializeJsonToByteBuffer(document);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs);
return requestObs.flatMap(req -> replace(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> patchDocument(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink");
checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations");
logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options));
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Patch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(
request,
null,
null,
options,
collectionObs);
return requestObs.flatMap(req -> patch(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy);
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Deleting a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs);
return requestObs.flatMap(req -> this
.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> this
.deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting documents due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Reading a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> {
return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Document>> readDocuments(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return queryDocuments(collectionLink, "SELECT * FROM r", options);
}
@Override
public <T> Mono<FeedResponse<T>> readMany(
List<CosmosItemIdentity> itemIdentityList,
String collectionLink,
CosmosQueryRequestOptions options,
Class<T> klass) {
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink, null
);
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request);
return collectionObs
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache
.tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null);
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap =
new HashMap<>();
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
itemIdentityList
.forEach(itemIdentity -> {
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(
itemIdentity.getPartitionKey()),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
if (partitionRangeItemKeyMap.get(range) == null) {
List<CosmosItemIdentity> list = new ArrayList<>();
list.add(itemIdentity);
partitionRangeItemKeyMap.put(range, list);
} else {
List<CosmosItemIdentity> pairs =
partitionRangeItemKeyMap.get(range);
pairs.add(itemIdentity);
partitionRangeItemKeyMap.put(range, pairs);
}
});
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap;
rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap,
collection.getPartitionKey());
return createReadManyQuery(
resourceLink,
new SqlQuerySpec(DUMMY_SQL_QUERY),
options,
Document.class,
ResourceType.Document,
collection,
Collections.unmodifiableMap(rangeQueryMap))
.collectList()
.map(feedList -> {
List<T> finalList = new ArrayList<>();
HashMap<String, String> headers = new HashMap<>();
ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>();
double requestCharge = 0;
for (FeedResponse<Document> page : feedList) {
ConcurrentMap<String, QueryMetrics> pageQueryMetrics =
ModelBridgeInternal.queryMetrics(page);
if (pageQueryMetrics != null) {
pageQueryMetrics.forEach(
aggregatedQueryMetrics::putIfAbsent);
}
requestCharge += page.getRequestCharge();
finalList.addAll(page.getResults().stream().map(document ->
ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList()));
}
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double
.toString(requestCharge));
FeedResponse<T> frp = BridgeInternal
.createFeedResponse(finalList, headers);
return frp;
});
});
}
);
}
private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap(
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap,
PartitionKeyDefinition partitionKeyDefinition) {
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>();
String partitionKeySelector = createPkSelector(partitionKeyDefinition);
for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) {
SqlQuerySpec sqlQuerySpec;
if (partitionKeySelector.equals("[\"id\"]")) {
sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector);
} else {
sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector);
}
rangeQueryMap.put(entry.getKey(), sqlQuerySpec);
}
return rangeQueryMap;
}
private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(
List<CosmosItemIdentity> idPartitionKeyPairList,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( ");
for (int i = 0; i < idPartitionKeyPairList.size(); i++) {
CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i);
String idValue = itemIdentity.getId();
String idParamName = "@param" + i;
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
if (!Objects.equals(idValue, pkValue)) {
continue;
}
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append(idParamName);
if (i < idPartitionKeyPairList.size() - 1) {
queryStringBuilder.append(", ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE ( ");
for (int i = 0; i < itemIdentities.size(); i++) {
CosmosItemIdentity itemIdentity = itemIdentities.get(i);
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
String pkParamName = "@param" + (2 * i);
parameters.add(new SqlParameter(pkParamName, pkValue));
String idValue = itemIdentity.getId();
String idParamName = "@param" + (2 * i + 1);
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append("(");
queryStringBuilder.append("c.id = ");
queryStringBuilder.append(idParamName);
queryStringBuilder.append(" AND ");
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
queryStringBuilder.append(" )");
if (i < itemIdentities.size() - 1) {
queryStringBuilder.append(" OR ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) {
return partitionKeyDefinition.getPaths()
.stream()
.map(pathPart -> StringUtils.substring(pathPart, 1))
.map(pathPart -> StringUtils.replace(pathPart, "\"", "\\"))
.map(part -> "[\"" + part + "\"]")
.collect(Collectors.joining());
}
private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
DocumentCollection collection,
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) {
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(),
sqlQuery,
rangeQueryMap,
options,
collection.getResourceId(),
parentResourceLink,
activityId,
klass,
resourceTypeEnum);
return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync);
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, String query, CosmosQueryRequestOptions options) {
return queryDocuments(collectionLink, new SqlQuerySpec(query), options);
}
private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return new IDocumentQueryClient () {
@Override
public RxCollectionCache getCollectionCache() {
return RxDocumentClientImpl.this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return RxDocumentClientImpl.this.partitionKeyRangeCache;
}
@Override
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy;
}
@Override
public ConsistencyLevel getDefaultConsistencyLevelAsync() {
return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel();
}
@Override
public ConsistencyLevel getDesiredConsistencyLevelAsync() {
return RxDocumentClientImpl.this.consistencyLevel;
}
@Override
public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) {
if (operationContextAndListenerTuple == null) {
return RxDocumentClientImpl.this.query(request).single();
} else {
final OperationListener listener =
operationContextAndListenerTuple.getOperationListener();
final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext();
request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId());
listener.requestListener(operationContext, request);
return RxDocumentClientImpl.this.query(request).single().doOnNext(
response -> listener.responseListener(operationContext, response)
).doOnError(
ex -> listener.exceptionListener(operationContext, ex)
);
}
}
@Override
public QueryCompatibilityMode getQueryCompatibilityMode() {
return QueryCompatibilityMode.Default;
}
@Override
public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) {
return null;
}
};
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
SqlQuerySpecLogger.getInstance().logQuery(querySpec);
return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document);
}
@Override
public Flux<FeedResponse<Document>> queryDocumentChangeFeed(
final DocumentCollection collection,
final CosmosChangeFeedRequestOptions changeFeedOptions) {
checkNotNull(collection, "Argument 'collection' must not be null.");
ChangeFeedQueryImpl<Document> changeFeedQueryImpl = new ChangeFeedQueryImpl<>(
this,
ResourceType.Document,
Document.class,
collection.getAltLink(),
collection.getResourceId(),
changeFeedOptions);
return changeFeedQueryImpl.executeAsync();
}
@Override
public Flux<FeedResponse<Document>> readAllDocuments(
String collectionLink,
PartitionKey partitionKey,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (partitionKey == null) {
throw new IllegalArgumentException("partitionKey");
}
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null
);
Flux<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request).flux();
return collectionObs.flatMap(documentCollectionResourceResponse -> {
DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
String pkSelector = createPkSelector(pkDefinition);
SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector);
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
final CosmosQueryRequestOptions effectiveOptions =
ModelBridgeInternal.createQueryRequestOptions(options);
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> {
Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache
.tryLookupAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null).flux();
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(partitionKey),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
return createQueryInternal(
resourceLink,
querySpec,
ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()),
Document.class,
ResourceType.Document,
queryClient,
activityId);
});
},
invalidPartitionExceptionRetryPolicy);
});
}
@Override
public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() {
return queryPlanCache;
}
@Override
public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class,
Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT));
}
private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
validateResource(storedProcedure);
String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType,
ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
return request;
}
private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (udf == null) {
throw new IllegalArgumentException("udf");
}
validateResource(udf);
String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Create);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId());
RxDocumentClientImpl.validateResource(storedProcedure);
String path = Utils.joinPath(storedProcedure.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class,
Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
List<Object> procedureParams) {
return this.executeStoredProcedure(storedProcedureLink, null, procedureParams);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy);
}
@Override
public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy);
}
private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) {
try {
logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript);
requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ExecuteJavaScript,
ResourceType.StoredProcedure, path,
procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "",
requestHeaders, options);
if (retryPolicy != null) {
retryPolicy.onBeforeSendRequest(request);
}
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options))
.map(response -> {
this.captureSessionToken(request, response);
return toStoredProcedureResponse(response);
}));
} catch (Exception e) {
logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
DocumentClientRetryPolicy requestRetryPolicy,
boolean disableAutomaticIdGeneration) {
try {
logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size());
Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true));
} catch (Exception ex) {
logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex);
return Mono.error(ex);
}
}
@Override
public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path,
trigger, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId());
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(trigger.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Trigger, Trigger.class,
Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryTriggers(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger);
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (udf == null) {
throw new IllegalArgumentException("udf");
}
logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId());
validateResource(udf);
String path = Utils.joinPath(udf.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class,
Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
String query, CosmosQueryRequestOptions options) {
return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction);
}
@Override
public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Conflict, Conflict.class,
Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryConflicts(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict);
}
@Override
public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (user == null) {
throw new IllegalArgumentException("user");
}
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.User, path, user, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (user == null) {
throw new IllegalArgumentException("user");
}
logger.debug("Replacing a User. user id [{}]", user.getId());
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(user.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.User, path, user, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Deleting a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Reading a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.User, User.class,
Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) {
return queryUsers(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User);
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(clientEncryptionKeyLink)) {
throw new IllegalArgumentException("clientEncryptionKeyLink");
}
logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink);
String path = Utils.joinPath(clientEncryptionKeyLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink,
ClientEncryptionKey clientEncryptionKey, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId());
RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey,
String nameBasedLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey,
nameBasedLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId());
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(nameBasedLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey,
OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders,
options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class,
Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey);
}
@Override
public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy());
}
private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
if (permission == null) {
throw new IllegalArgumentException("permission");
}
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Permission, path, permission, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (permission == null) {
throw new IllegalArgumentException("permission");
}
logger.debug("Replacing a Permission. permission id [{}]", permission.getId());
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(permission.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Reading a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
return readFeed(options, ResourceType.Permission, Permission.class,
Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query,
CosmosQueryRequestOptions options) {
return queryPermissions(userLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission);
}
@Override
public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
if (offer == null) {
throw new IllegalArgumentException("offer");
}
logger.debug("Replacing an Offer. offer id [{}]", offer.getId());
RxDocumentClientImpl.validateResource(offer);
String path = Utils.joinPath(offer.getSelfLink(), null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace,
ResourceType.Offer, path, offer, null, null);
return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Offer>> readOffer(String offerLink) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(offerLink)) {
throw new IllegalArgumentException("offerLink");
}
logger.debug("Reading an Offer. offerLink [{}]", offerLink);
String path = Utils.joinPath(offerLink, null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Offer, Offer.class,
Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null));
}
private <T extends Resource> Flux<FeedResponse<T>> readFeed(CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options);
int maxPageSize = maxItemCount != null ? maxItemCount : -1;
final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options;
DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> {
Map<String, String> requestHeaders = new HashMap<>();
if (continuationToken != null) {
requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken);
}
requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize));
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions);
retryPolicy.onBeforeSendRequest(request);
return request;
};
Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper
.inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)),
retryPolicy);
return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, maxPageSize);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) {
return queryOffers(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer);
}
@Override
public Mono<DatabaseAccount> getDatabaseAccount() {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy),
documentClientRetryPolicy);
}
@Override
public DatabaseAccount getLatestDatabaseAccount() {
return this.globalEndpointManager.getLatestDatabaseAccount();
}
private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Getting Database Account");
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read,
ResourceType.DatabaseAccount, "",
(HashMap<String, String>) null,
null);
return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount);
} catch (Exception e) {
logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Object getSession() {
return this.sessionContainer;
}
public void setSession(Object sessionContainer) {
this.sessionContainer = (SessionContainer) sessionContainer;
}
@Override
public RxClientCollectionCache getCollectionCache() {
return this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return partitionKeyRangeCache;
}
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
return Flux.defer(() -> {
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null);
return this.populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
requestPopulated.setEndpointOverride(endpoint);
return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> {
String message = String.format("Failed to retrieve database account information. %s",
e.getCause() != null
? e.getCause().toString()
: e.toString());
logger.warn(message);
}).map(rsp -> rsp.getResource(DatabaseAccount.class))
.doOnNext(databaseAccount ->
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled()
&& BridgeInternal.isEnableMultipleWriteLocations(databaseAccount));
});
});
}
/**
* Certain requests must be routed through gateway even when the client connectivity mode is direct.
*
* @param request
* @return RxStoreModel
*/
private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) {
if (request.UseGatewayMode) {
return this.gatewayProxy;
}
ResourceType resourceType = request.getResourceType();
OperationType operationType = request.getOperationType();
if (resourceType == ResourceType.Offer ||
resourceType == ResourceType.ClientEncryptionKey ||
resourceType.isScript() && operationType != OperationType.ExecuteJavaScript ||
resourceType == ResourceType.PartitionKeyRange ||
resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) {
return this.gatewayProxy;
}
if (operationType == OperationType.Create
|| operationType == OperationType.Upsert) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection ||
resourceType == ResourceType.Permission) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Delete) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Replace) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Read) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else {
if ((operationType == OperationType.Query ||
operationType == OperationType.SqlQuery ||
operationType == OperationType.ReadFeed) &&
Utils.isCollectionChild(request.getResourceType())) {
if (request.getPartitionKeyRangeIdentity() == null &&
request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) {
return this.gatewayProxy;
}
}
return this.storeModel;
}
}
@Override
public void close() {
logger.info("Attempting to close client {}", this.clientId);
if (!closed.getAndSet(true)) {
logger.info("Shutting down ...");
logger.info("Closing Global Endpoint Manager ...");
LifeCycleUtils.closeQuietly(this.globalEndpointManager);
logger.info("Closing StoreClientFactory ...");
LifeCycleUtils.closeQuietly(this.storeClientFactory);
logger.info("Shutting down reactorHttpClient ...");
LifeCycleUtils.closeQuietly(this.reactorHttpClient);
logger.info("Shutting down CpuMonitor ...");
CpuMemoryMonitor.unregister(this);
if (this.throughputControlEnabled.get()) {
logger.info("Closing ThroughputControlStore ...");
this.throughputControlStore.close();
}
logger.info("Shutting down completed.");
} else {
logger.warn("Already shutdown!");
}
}
@Override
public ItemDeserializer getItemDeserializer() {
return this.itemDeserializer;
}
@Override
public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group can not be null");
if (this.throughputControlEnabled.compareAndSet(false, true)) {
this.throughputControlStore =
new ThroughputControlStore(
this.collectionCache,
this.connectionPolicy.getConnectionMode(),
this.partitionKeyRangeCache);
this.storeModel.enableThroughputControl(throughputControlStore);
}
this.throughputControlStore.enableThroughputControlGroup(group);
}
private static SqlQuerySpec createLogicalPartitionScanQuerySpec(
PartitionKey partitionKey,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE");
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey);
String pkParamName = "@pkValue";
parameters.add(new SqlParameter(pkParamName, pkValue));
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
@Override
public Mono<List<FeedRange>> getFeedRanges(String collectionLink) {
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
collectionLink,
new HashMap<>());
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null);
invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request);
return ObservableHelper.inlineIfPossibleAsObs(
() -> getFeedRangesInternal(request, collectionLink),
invalidPartitionExceptionRetryPolicy);
}
private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) {
logger.debug("getFeedRange collectionLink=[{}]", collectionLink);
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null,
request);
return collectionObs.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache
.tryGetOverlappingRangesAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null);
return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request));
});
}
private static List<FeedRange> toFeedRanges(
Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) {
final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v;
if (partitionKeyRangeList == null) {
request.forceNameCacheRefresh = true;
throw new InvalidPartitionException();
}
List<FeedRange> feedRanges = new ArrayList<>();
partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange)));
return feedRanges;
}
private static FeedRange toFeedRange(PartitionKeyRange pkRange) {
return new FeedRangeEpkImpl(pkRange.toRange());
}
} | class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener,
DiagnosticsClientContext {
private static final String tempMachineId = "uuid:" + UUID.randomUUID();
private static final AtomicInteger activeClientsCnt = new AtomicInteger(0);
private static final AtomicInteger clientIdGenerator = new AtomicInteger(0);
private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>(
PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey,
PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false);
private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " +
"ParallelDocumentQueryExecutioncontext, but not used";
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper();
private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer();
private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class);
private final String masterKeyOrResourceToken;
private final URI serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel consistencyLevel;
private final BaseAuthorizationTokenProvider authorizationTokenProvider;
private final UserAgentContainer userAgentContainer;
private final boolean hasAuthKeyResourceToken;
private final Configs configs;
private final boolean connectionSharingAcrossClientsEnabled;
private AzureKeyCredential credential;
private final TokenCredential tokenCredential;
private String[] tokenCredentialScopes;
private SimpleTokenCache tokenCredentialCache;
private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver;
AuthorizationTokenType authorizationTokenType;
private SessionContainer sessionContainer;
private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY;
private RxClientCollectionCache collectionCache;
private RxStoreModel gatewayProxy;
private RxStoreModel storeModel;
private GlobalAddressResolver addressResolver;
private RxPartitionKeyRangeCache partitionKeyRangeCache;
private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap;
private final boolean contentResponseOnWriteEnabled;
private Map<String, PartitionedQueryExecutionInfo> queryPlanCache;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final int clientId;
private ClientTelemetry clientTelemetry;
private ApiType apiType;
private IRetryPolicyFactory resetSessionTokenRetryPolicy;
/**
* Compatibility mode: Allows to specify compatibility mode used by client when
* making query requests. Should be removed when application/sql is no longer
* supported.
*/
private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default;
private final GlobalEndpointManager globalEndpointManager;
private final RetryPolicy retryPolicy;
private HttpClient reactorHttpClient;
private Function<HttpClient, HttpClient> httpClientInterceptor;
private volatile boolean useMultipleWriteLocations;
private StoreClientFactory storeClientFactory;
private GatewayServiceConfigurationReader gatewayConfigurationReader;
private final DiagnosticsClientConfig diagnosticsClientConfig;
private final AtomicBoolean throughputControlEnabled;
private ThroughputControlStore throughputControlStore;
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
private RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
if (permissionFeed != null && permissionFeed.size() > 0) {
this.resourceTokensMap = new HashMap<>();
for (Permission permission : permissionFeed) {
String[] segments = StringUtils.split(permission.getResourceLink(),
Constants.Properties.PATH_SEPARATOR.charAt(0));
if (segments.length <= 0) {
throw new IllegalArgumentException("resourceLink");
}
List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null;
PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false);
if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) {
throw new IllegalArgumentException(permission.getResourceLink());
}
partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName);
if (partitionKeyAndResourceTokenPairs == null) {
partitionKeyAndResourceTokenPairs = new ArrayList<>();
this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs);
}
PartitionKey partitionKey = permission.getResourcePartitionKey();
partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair(
partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty,
permission.getToken()));
logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]",
pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken());
}
if(this.resourceTokensMap.isEmpty()) {
throw new IllegalArgumentException("permissionFeed");
}
String firstToken = permissionFeed.get(0).getToken();
if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) {
this.firstResourceTokenFromPermissionFeed = firstToken;
}
}
}
RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
activeClientsCnt.incrementAndGet();
this.clientId = clientIdGenerator.incrementAndGet();
this.diagnosticsClientConfig = new DiagnosticsClientConfig();
this.diagnosticsClientConfig.withClientId(this.clientId);
this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt);
this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled);
this.diagnosticsClientConfig.withConsistency(consistencyLevel);
this.throughputControlEnabled = new AtomicBoolean(false);
logger.info(
"Initializing DocumentClient [{}] with"
+ " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]",
this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol());
try {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
this.configs = configs;
this.masterKeyOrResourceToken = masterKeyOrResourceToken;
this.serviceEndpoint = serviceEndpoint;
this.credential = credential;
this.tokenCredential = tokenCredential;
this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled;
this.authorizationTokenType = AuthorizationTokenType.Invalid;
if (this.credential != null) {
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.authorizationTokenProvider = null;
hasAuthKeyResourceToken = true;
this.authorizationTokenType = AuthorizationTokenType.ResourceToken;
} else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken);
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else {
hasAuthKeyResourceToken = false;
this.authorizationTokenProvider = null;
if (tokenCredential != null) {
this.tokenCredentialScopes = new String[] {
serviceEndpoint.getScheme() + ":
};
this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential
.getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes)));
this.authorizationTokenType = AuthorizationTokenType.AadToken;
}
}
if (connectionPolicy != null) {
this.connectionPolicy = connectionPolicy;
} else {
this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig());
}
this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode());
this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled());
this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled());
this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions());
this.diagnosticsClientConfig.withMachineId(tempMachineId);
boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled);
this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing);
this.consistencyLevel = consistencyLevel;
this.userAgentContainer = new UserAgentContainer();
String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix();
if (userAgentSuffix != null && userAgentSuffix.length() > 0) {
userAgentContainer.setSuffix(userAgentSuffix);
}
this.httpClientInterceptor = null;
this.reactorHttpClient = httpClient();
this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs);
this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy);
this.resetSessionTokenRetryPolicy = retryPolicy;
CpuMemoryMonitor.register(this);
this.queryPlanCache = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE));
this.apiType = apiType;
} catch (RuntimeException e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
}
@Override
public DiagnosticsClientConfig getConfig() {
return diagnosticsClientConfig;
}
@Override
public CosmosDiagnostics createDiagnostics() {
return BridgeInternal.createCosmosDiagnostics(this, this.globalEndpointManager);
}
private void initializeGatewayConfigurationReader() {
this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager);
DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount();
if (databaseAccount == null) {
logger.error("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
throw new RuntimeException("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
}
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount);
}
private void updateGatewayProxy() {
((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader);
((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache);
((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache);
((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations);
}
public void serialize(CosmosClientMetadataCachesSnapshot state) {
RxCollectionCache.serialize(state, this.collectionCache);
}
private void initializeDirectConnectivity() {
this.addressResolver = new GlobalAddressResolver(this,
this.reactorHttpClient,
this.globalEndpointManager,
this.configs.getProtocol(),
this,
this.collectionCache,
this.partitionKeyRangeCache,
userAgentContainer,
null,
this.connectionPolicy,
this.apiType);
this.storeClientFactory = new StoreClientFactory(
this.addressResolver,
this.diagnosticsClientConfig,
this.configs,
this.connectionPolicy,
this.userAgentContainer,
this.connectionSharingAcrossClientsEnabled,
this.clientTelemetry
);
this.createStoreModel(true);
}
DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() {
return new DatabaseAccountManagerInternal() {
@Override
public URI getServiceEndpoint() {
return RxDocumentClientImpl.this.getServiceEndpoint();
}
@Override
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
logger.info("Getting database account endpoint from {}", endpoint);
return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return RxDocumentClientImpl.this.getConnectionPolicy();
}
};
}
RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer,
ConsistencyLevel consistencyLevel,
QueryCompatibilityMode queryCompatibilityMode,
UserAgentContainer userAgentContainer,
GlobalEndpointManager globalEndpointManager,
HttpClient httpClient,
ApiType apiType) {
return new RxGatewayStoreModel(
this,
sessionContainer,
consistencyLevel,
queryCompatibilityMode,
userAgentContainer,
globalEndpointManager,
httpClient,
apiType);
}
private HttpClient httpClient() {
HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs)
.withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout())
.withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize())
.withProxy(this.connectionPolicy.getProxy())
.withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout());
if (connectionSharingAcrossClientsEnabled) {
return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig);
} else {
diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig);
return HttpClient.createFixed(httpClientConfig);
}
}
private void createStoreModel(boolean subscribeRntbdStatus) {
StoreClient storeClient = this.storeClientFactory.createStoreClient(this,
this.addressResolver,
this.sessionContainer,
this.gatewayConfigurationReader,
this,
this.useMultipleWriteLocations
);
this.storeModel = new ServerStoreModel(storeClient);
}
@Override
public URI getServiceEndpoint() {
return this.serviceEndpoint;
}
@Override
public URI getWriteEndpoint() {
return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null);
}
@Override
public URI getReadEndpoint() {
return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return this.connectionPolicy;
}
@Override
public boolean isContentResponseOnWriteEnabled() {
return contentResponseOnWriteEnabled;
}
@Override
public ConsistencyLevel getConsistencyLevel() {
return consistencyLevel;
}
@Override
public ClientTelemetry getClientTelemetry() {
return this.clientTelemetry;
}
@Override
public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (database == null) {
throw new IllegalArgumentException("Database");
}
logger.debug("Creating a Database. id: [{}]", database.getId());
validateResource(database);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Reading a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT);
}
private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) {
switch (resourceTypeEnum) {
case Database:
return Paths.DATABASES_ROOT;
case DocumentCollection:
return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT);
case Document:
return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT);
case Offer:
return Paths.OFFERS_ROOT;
case User:
return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT);
case ClientEncryptionKey:
return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
case Permission:
return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT);
case Attachment:
return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT);
case StoredProcedure:
return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
case Trigger:
return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT);
case UserDefinedFunction:
return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
case Conflict:
return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT);
default:
throw new IllegalArgumentException("resource type not supported");
}
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) {
if (options == null) {
return null;
}
return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options);
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) {
if (options == null) {
return null;
}
return options.getOperationContextAndListenerTuple();
}
private <T extends Resource> Flux<FeedResponse<T>> createQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum) {
String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum);
UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getCorrelationActivityId(options);
UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ?
correlationActivityIdOfRequestOptions : Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this,
getOperationContextAndListenerTuple(options));
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> createQueryInternal(
resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId),
invalidPartitionExceptionRetryPolicy);
}
private <T extends Resource> Flux<FeedResponse<T>> createQueryInternal(
String resourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
IDocumentQueryClient queryClient,
UUID activityId) {
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory
.createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery,
options, resourceLink, false, activityId,
Configs.isQueryPlanCachingEnabled(), queryPlanCache);
AtomicBoolean isFirstResponse = new AtomicBoolean(true);
return executionContext.flatMap(iDocumentQueryExecutionContext -> {
QueryInfo queryInfo = null;
if (iDocumentQueryExecutionContext instanceof PipelinedDocumentQueryExecutionContext) {
queryInfo = ((PipelinedDocumentQueryExecutionContext<T>) iDocumentQueryExecutionContext).getQueryInfo();
}
QueryInfo finalQueryInfo = queryInfo;
return iDocumentQueryExecutionContext.executeAsync()
.map(tFeedResponse -> {
if (finalQueryInfo != null) {
if (finalQueryInfo.hasSelectValue()) {
ModelBridgeInternal
.addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo);
}
if (isFirstResponse.compareAndSet(true, false)) {
ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse,
finalQueryInfo.getQueryPlanDiagnosticsContext());
}
}
return tFeedResponse;
});
});
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) {
return queryDatabases(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database);
}
@Override
public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink,
DocumentCollection collection, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink,
DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink,
collection.getId());
validateResource(collection);
String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
});
} catch (Exception e) {
logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Replacing a Collection. id: [{}]", collection.getId());
validateResource(collection);
String path = Utils.joinPath(collection.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
if (resourceResponse.getResource() != null) {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
}
});
} catch (Exception e) {
logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.DELETE)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated));
}
private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated ->
this.getStoreProxy(requestPopulated).processMessage(requestPopulated)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
));
}
@Override
public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class,
Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection);
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection);
}
private static String serializeProcedureParams(List<Object> objectArray) {
String[] stringArray = new String[objectArray.size()];
for (int i = 0; i < objectArray.size(); ++i) {
Object object = objectArray.get(i);
if (object instanceof JsonSerializable) {
stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object);
} else {
try {
stringArray[i] = mapper.writeValueAsString(object);
} catch (IOException e) {
throw new IllegalArgumentException("Can't serialize the object into the json string", e);
}
}
}
return String.format("[%s]", StringUtils.join(stringArray, ","));
}
private static void validateResource(Resource resource) {
if (!StringUtils.isEmpty(resource.getId())) {
if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 ||
resource.getId().indexOf('?') != -1 || resource.getId().indexOf('
throw new IllegalArgumentException("Id contains illegal chars.");
}
if (resource.getId().endsWith(" ")) {
throw new IllegalArgumentException("Id ends with a space.");
}
}
}
private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) {
Map<String, String> headers = new HashMap<>();
if (this.useMultipleWriteLocations) {
headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString());
}
if (consistencyLevel != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString());
}
if (options == null) {
if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
return headers;
}
Map<String, String> customOptions = options.getHeaders();
if (customOptions != null) {
headers.putAll(customOptions);
}
boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled;
if (options.isContentResponseOnWriteEnabled() != null) {
contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled();
}
if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
if (options.getIfMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag());
}
if(options.getIfNoneMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag());
}
if (options.getConsistencyLevel() != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString());
}
if (options.getIndexingDirective() != null) {
headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString());
}
if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) {
String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude);
}
if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) {
String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude);
}
if (!Strings.isNullOrEmpty(options.getSessionToken())) {
headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken());
}
if (options.getResourceTokenExpirySeconds() != null) {
headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY,
String.valueOf(options.getResourceTokenExpirySeconds()));
}
if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString());
} else if (options.getOfferType() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType());
}
if (options.getOfferThroughput() == null) {
if (options.getThroughputProperties() != null) {
Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties());
final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings();
OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null;
if (offerAutoscaleSettings != null) {
autoscaleAutoUpgradeProperties
= offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties();
}
if (offer.hasOfferThroughput() &&
(offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 ||
autoscaleAutoUpgradeProperties != null &&
autoscaleAutoUpgradeProperties
.getAutoscaleThroughputProperties()
.getIncrementPercent() >= 0)) {
throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with "
+ "fixed offer");
}
if (offer.hasOfferThroughput()) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput()));
} else if (offer.getOfferAutoScaleSettings() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS,
ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings()));
}
}
}
if (options.isQuotaInfoEnabled()) {
headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true));
}
if (options.isScriptLoggingEnabled()) {
headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true));
}
if (options.getDedicatedGatewayRequestOptions() != null &&
options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) {
headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS,
String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions())));
}
return headers;
}
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return this.resetSessionTokenRetryPolicy;
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Document document,
RequestOptions options) {
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs
.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object document,
RequestOptions options,
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) {
return collectionObs.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private void addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object objectDoc, RequestOptions options,
DocumentCollection collection) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
PartitionKeyInternal partitionKeyInternal = null;
if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else if (options != null && options.getPartitionKey() != null) {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey());
} else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) {
partitionKeyInternal = PartitionKeyInternal.getEmpty();
} else if (contentAsByteBuffer != null || objectDoc != null) {
InternalObjectNode internalObjectNode;
if (objectDoc instanceof InternalObjectNode) {
internalObjectNode = (InternalObjectNode) objectDoc;
} else if (objectDoc instanceof ObjectNode) {
internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc);
} else if (contentAsByteBuffer != null) {
contentAsByteBuffer.rewind();
internalObjectNode = new InternalObjectNode(contentAsByteBuffer);
} else {
throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null");
}
Instant serializationStartTime = Instant.now();
partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTime,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION
);
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
} else {
throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation.");
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
}
public static PartitionKeyInternal extractPartitionKeyValueFromDocument(
InternalObjectNode document,
PartitionKeyDefinition partitionKeyDefinition) {
if (partitionKeyDefinition != null) {
switch (partitionKeyDefinition.getKind()) {
case HASH:
String path = partitionKeyDefinition.getPaths().iterator().next();
List<String> parts = PathParser.getPathParts(path);
if (parts.size() >= 1) {
Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts);
if (value == null || value.getClass() == ObjectNode.class) {
value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
}
if (value instanceof PartitionKeyInternal) {
return (PartitionKeyInternal) value;
} else {
return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false);
}
}
break;
case MULTI_HASH:
Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()];
for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){
String partitionPath = partitionKeyDefinition.getPaths().get(pathIter);
List<String> partitionPathParts = PathParser.getPathParts(partitionPath);
partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts);
}
return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false);
default:
throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind());
}
}
return null;
}
private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
Object document,
RequestOptions options,
boolean disableAutomaticIdGeneration,
OperationType operationType) {
if (StringUtils.isEmpty(documentCollectionLink)) {
throw new IllegalArgumentException("documentCollectionLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Document, path, requestHeaders, options, content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return addPartitionKeyInformation(request, content, document, options, collectionObs);
}
private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink");
checkNotNull(serverBatchRequest, "expected non null serverBatchRequest");
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody()));
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Batch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> {
addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v);
return request;
});
}
private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request,
ServerBatchRequest serverBatchRequest,
DocumentCollection collection) {
if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) {
PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue();
PartitionKeyInternal partitionKeyInternal;
if (partitionKey.equals(PartitionKey.NONE)) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey);
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
} else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) {
request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId()));
} else {
throw new UnsupportedOperationException("Unknown Server request.");
}
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString());
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch()));
request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError()));
request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size());
return request;
}
private Mono<RxDocumentServiceRequest> populateHeaders(RxDocumentServiceRequest request, RequestVerb httpMethod) {
request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123());
if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null
|| this.cosmosAuthorizationTokenResolver != null || this.credential != null) {
String resourceName = request.getResourceAddress();
String authorization = this.getUserAuthorizationToken(
resourceName, request.getResourceType(), httpMethod, request.getHeaders(),
AuthorizationTokenType.PrimaryMasterKey, request.properties);
try {
authorization = URLEncoder.encode(authorization, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Failed to encode authtoken.", e);
}
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
}
if (this.apiType != null) {
request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString());
}
if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod))
&& !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
}
if (RequestVerb.PATCH.equals(httpMethod) &&
!request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH);
}
if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) {
request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
}
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
if (this.requiresFeedRangeFiltering(request)) {
return request.getFeedRange()
.populateFeedRangeFilteringHeaders(
this.getPartitionKeyRangeCache(),
request,
this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request))
.flatMap(this::populateAuthorizationHeader);
}
return this.populateAuthorizationHeader(request);
}
private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) {
if (request.getResourceType() != ResourceType.Document &&
request.getResourceType() != ResourceType.Conflict) {
return false;
}
switch (request.getOperationType()) {
case ReadFeed:
case Query:
case SqlQuery:
return request.getFeedRange() != null;
default:
return false;
}
}
@Override
public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) {
if (request == null) {
throw new IllegalArgumentException("request");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return request;
});
} else {
return Mono.just(request);
}
}
@Override
public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) {
if (httpHeaders == null) {
throw new IllegalArgumentException("httpHeaders");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return httpHeaders;
});
}
return Mono.just(httpHeaders);
}
@Override
public AuthorizationTokenType getAuthorizationTokenType() {
return this.authorizationTokenType;
}
@Override
public String getUserAuthorizationToken(String resourceName,
ResourceType resourceType,
RequestVerb requestVerb,
Map<String, String> headers,
AuthorizationTokenType tokenType,
Map<String, Object> properties) {
if (this.cosmosAuthorizationTokenResolver != null) {
return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(),
properties != null ? Collections.unmodifiableMap(properties) : null);
} else if (credential != null) {
return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName,
resourceType, headers);
} else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) {
return masterKeyOrResourceToken;
} else {
assert resourceTokensMap != null;
if(resourceType.equals(ResourceType.DatabaseAccount)) {
return this.firstResourceTokenFromPermissionFeed;
}
return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers);
}
}
private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) {
CosmosResourceType cosmosResourceType =
ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString());
if (cosmosResourceType == null) {
return CosmosResourceType.SYSTEM;
}
return cosmosResourceType;
}
void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) {
this.sessionContainer.setSessionToken(request, response.getResponseHeaders());
}
private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
Map<String, String> headers = requestPopulated.getHeaders();
assert (headers != null);
headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true");
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
);
});
}
private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.PUT)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PATCH);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(request).processMessage(request);
}
@Override
public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) {
try {
logger.debug("Creating a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Create);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance);
}
private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Upsert);
Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = Utils.getCollectionName(documentLink);
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Document typedDocument = documentFromObject(document, mapper);
return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = document.getSelfLink();
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (document == null) {
throw new IllegalArgumentException("document");
}
return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a database due to [{}]", e.getMessage());
return Mono.error(e);
}
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink,
Document document,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
if (document == null) {
throw new IllegalArgumentException("document");
}
logger.debug("Replacing a Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = serializeJsonToByteBuffer(document);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs);
return requestObs.flatMap(req -> replace(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> patchDocument(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink");
checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations");
logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options));
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Patch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(
request,
null,
null,
options,
collectionObs);
return requestObs.flatMap(req -> patch(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy);
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Deleting a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs);
return requestObs.flatMap(req -> this
.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> this
.deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting documents due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Reading a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> {
return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Document>> readDocuments(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return queryDocuments(collectionLink, "SELECT * FROM r", options);
}
@Override
public <T> Mono<FeedResponse<T>> readMany(
List<CosmosItemIdentity> itemIdentityList,
String collectionLink,
CosmosQueryRequestOptions options,
Class<T> klass) {
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink, null
);
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request);
return collectionObs
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache
.tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null);
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap =
new HashMap<>();
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
itemIdentityList
.forEach(itemIdentity -> {
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(
itemIdentity.getPartitionKey()),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
if (partitionRangeItemKeyMap.get(range) == null) {
List<CosmosItemIdentity> list = new ArrayList<>();
list.add(itemIdentity);
partitionRangeItemKeyMap.put(range, list);
} else {
List<CosmosItemIdentity> pairs =
partitionRangeItemKeyMap.get(range);
pairs.add(itemIdentity);
partitionRangeItemKeyMap.put(range, pairs);
}
});
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap;
rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap,
collection.getPartitionKey());
return createReadManyQuery(
resourceLink,
new SqlQuerySpec(DUMMY_SQL_QUERY),
options,
Document.class,
ResourceType.Document,
collection,
Collections.unmodifiableMap(rangeQueryMap))
.collectList()
.map(feedList -> {
List<T> finalList = new ArrayList<>();
HashMap<String, String> headers = new HashMap<>();
ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>();
double requestCharge = 0;
for (FeedResponse<Document> page : feedList) {
ConcurrentMap<String, QueryMetrics> pageQueryMetrics =
ModelBridgeInternal.queryMetrics(page);
if (pageQueryMetrics != null) {
pageQueryMetrics.forEach(
aggregatedQueryMetrics::putIfAbsent);
}
requestCharge += page.getRequestCharge();
finalList.addAll(page.getResults().stream().map(document ->
ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList()));
}
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double
.toString(requestCharge));
FeedResponse<T> frp = BridgeInternal
.createFeedResponse(finalList, headers);
return frp;
});
});
}
);
}
private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap(
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap,
PartitionKeyDefinition partitionKeyDefinition) {
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>();
String partitionKeySelector = createPkSelector(partitionKeyDefinition);
for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) {
SqlQuerySpec sqlQuerySpec;
if (partitionKeySelector.equals("[\"id\"]")) {
sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector);
} else {
sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector);
}
rangeQueryMap.put(entry.getKey(), sqlQuerySpec);
}
return rangeQueryMap;
}
private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(
List<CosmosItemIdentity> idPartitionKeyPairList,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( ");
for (int i = 0; i < idPartitionKeyPairList.size(); i++) {
CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i);
String idValue = itemIdentity.getId();
String idParamName = "@param" + i;
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
if (!Objects.equals(idValue, pkValue)) {
continue;
}
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append(idParamName);
if (i < idPartitionKeyPairList.size() - 1) {
queryStringBuilder.append(", ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE ( ");
for (int i = 0; i < itemIdentities.size(); i++) {
CosmosItemIdentity itemIdentity = itemIdentities.get(i);
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
String pkParamName = "@param" + (2 * i);
parameters.add(new SqlParameter(pkParamName, pkValue));
String idValue = itemIdentity.getId();
String idParamName = "@param" + (2 * i + 1);
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append("(");
queryStringBuilder.append("c.id = ");
queryStringBuilder.append(idParamName);
queryStringBuilder.append(" AND ");
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
queryStringBuilder.append(" )");
if (i < itemIdentities.size() - 1) {
queryStringBuilder.append(" OR ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) {
return partitionKeyDefinition.getPaths()
.stream()
.map(pathPart -> StringUtils.substring(pathPart, 1))
.map(pathPart -> StringUtils.replace(pathPart, "\"", "\\"))
.map(part -> "[\"" + part + "\"]")
.collect(Collectors.joining());
}
private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
DocumentCollection collection,
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) {
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(),
sqlQuery,
rangeQueryMap,
options,
collection.getResourceId(),
parentResourceLink,
activityId,
klass,
resourceTypeEnum);
return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync);
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, String query, CosmosQueryRequestOptions options) {
return queryDocuments(collectionLink, new SqlQuerySpec(query), options);
}
private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return new IDocumentQueryClient () {
@Override
public RxCollectionCache getCollectionCache() {
return RxDocumentClientImpl.this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return RxDocumentClientImpl.this.partitionKeyRangeCache;
}
@Override
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy;
}
@Override
public ConsistencyLevel getDefaultConsistencyLevelAsync() {
return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel();
}
@Override
public ConsistencyLevel getDesiredConsistencyLevelAsync() {
return RxDocumentClientImpl.this.consistencyLevel;
}
@Override
public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) {
if (operationContextAndListenerTuple == null) {
return RxDocumentClientImpl.this.query(request).single();
} else {
final OperationListener listener =
operationContextAndListenerTuple.getOperationListener();
final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext();
request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId());
listener.requestListener(operationContext, request);
return RxDocumentClientImpl.this.query(request).single().doOnNext(
response -> listener.responseListener(operationContext, response)
).doOnError(
ex -> listener.exceptionListener(operationContext, ex)
);
}
}
@Override
public QueryCompatibilityMode getQueryCompatibilityMode() {
return QueryCompatibilityMode.Default;
}
@Override
public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) {
return null;
}
};
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
SqlQuerySpecLogger.getInstance().logQuery(querySpec);
return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document);
}
@Override
public Flux<FeedResponse<Document>> queryDocumentChangeFeed(
final DocumentCollection collection,
final CosmosChangeFeedRequestOptions changeFeedOptions) {
checkNotNull(collection, "Argument 'collection' must not be null.");
ChangeFeedQueryImpl<Document> changeFeedQueryImpl = new ChangeFeedQueryImpl<>(
this,
ResourceType.Document,
Document.class,
collection.getAltLink(),
collection.getResourceId(),
changeFeedOptions);
return changeFeedQueryImpl.executeAsync();
}
@Override
public Flux<FeedResponse<Document>> readAllDocuments(
String collectionLink,
PartitionKey partitionKey,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (partitionKey == null) {
throw new IllegalArgumentException("partitionKey");
}
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null
);
Flux<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request).flux();
return collectionObs.flatMap(documentCollectionResourceResponse -> {
DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
String pkSelector = createPkSelector(pkDefinition);
SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector);
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
final CosmosQueryRequestOptions effectiveOptions =
ModelBridgeInternal.createQueryRequestOptions(options);
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> {
Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache
.tryLookupAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null).flux();
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(partitionKey),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
return createQueryInternal(
resourceLink,
querySpec,
ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()),
Document.class,
ResourceType.Document,
queryClient,
activityId);
});
},
invalidPartitionExceptionRetryPolicy);
});
}
@Override
public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() {
return queryPlanCache;
}
@Override
public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class,
Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT));
}
private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
validateResource(storedProcedure);
String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType,
ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
return request;
}
private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (udf == null) {
throw new IllegalArgumentException("udf");
}
validateResource(udf);
String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Create);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId());
RxDocumentClientImpl.validateResource(storedProcedure);
String path = Utils.joinPath(storedProcedure.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class,
Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
List<Object> procedureParams) {
return this.executeStoredProcedure(storedProcedureLink, null, procedureParams);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy);
}
@Override
public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy);
}
private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) {
try {
logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript);
requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ExecuteJavaScript,
ResourceType.StoredProcedure, path,
procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "",
requestHeaders, options);
if (retryPolicy != null) {
retryPolicy.onBeforeSendRequest(request);
}
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options))
.map(response -> {
this.captureSessionToken(request, response);
return toStoredProcedureResponse(response);
}));
} catch (Exception e) {
logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
DocumentClientRetryPolicy requestRetryPolicy,
boolean disableAutomaticIdGeneration) {
try {
logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size());
Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true));
} catch (Exception ex) {
logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex);
return Mono.error(ex);
}
}
@Override
public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path,
trigger, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId());
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(trigger.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Trigger, Trigger.class,
Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryTriggers(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger);
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (udf == null) {
throw new IllegalArgumentException("udf");
}
logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId());
validateResource(udf);
String path = Utils.joinPath(udf.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class,
Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
String query, CosmosQueryRequestOptions options) {
return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction);
}
@Override
public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Conflict, Conflict.class,
Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryConflicts(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict);
}
@Override
public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (user == null) {
throw new IllegalArgumentException("user");
}
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.User, path, user, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (user == null) {
throw new IllegalArgumentException("user");
}
logger.debug("Replacing a User. user id [{}]", user.getId());
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(user.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.User, path, user, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Deleting a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Reading a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.User, User.class,
Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) {
return queryUsers(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User);
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(clientEncryptionKeyLink)) {
throw new IllegalArgumentException("clientEncryptionKeyLink");
}
logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink);
String path = Utils.joinPath(clientEncryptionKeyLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink,
ClientEncryptionKey clientEncryptionKey, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId());
RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey,
String nameBasedLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey,
nameBasedLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId());
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(nameBasedLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey,
OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders,
options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class,
Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey);
}
@Override
public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy());
}
private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
if (permission == null) {
throw new IllegalArgumentException("permission");
}
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Permission, path, permission, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (permission == null) {
throw new IllegalArgumentException("permission");
}
logger.debug("Replacing a Permission. permission id [{}]", permission.getId());
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(permission.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Reading a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
return readFeed(options, ResourceType.Permission, Permission.class,
Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query,
CosmosQueryRequestOptions options) {
return queryPermissions(userLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission);
}
@Override
public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
if (offer == null) {
throw new IllegalArgumentException("offer");
}
logger.debug("Replacing an Offer. offer id [{}]", offer.getId());
RxDocumentClientImpl.validateResource(offer);
String path = Utils.joinPath(offer.getSelfLink(), null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace,
ResourceType.Offer, path, offer, null, null);
return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Offer>> readOffer(String offerLink) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(offerLink)) {
throw new IllegalArgumentException("offerLink");
}
logger.debug("Reading an Offer. offerLink [{}]", offerLink);
String path = Utils.joinPath(offerLink, null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Offer, Offer.class,
Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null));
}
private <T extends Resource> Flux<FeedResponse<T>> readFeed(CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options);
int maxPageSize = maxItemCount != null ? maxItemCount : -1;
final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options;
DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> {
Map<String, String> requestHeaders = new HashMap<>();
if (continuationToken != null) {
requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken);
}
requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize));
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions);
retryPolicy.onBeforeSendRequest(request);
return request;
};
Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper
.inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)),
retryPolicy);
return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, maxPageSize);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) {
return queryOffers(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer);
}
@Override
public Mono<DatabaseAccount> getDatabaseAccount() {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy),
documentClientRetryPolicy);
}
@Override
public DatabaseAccount getLatestDatabaseAccount() {
return this.globalEndpointManager.getLatestDatabaseAccount();
}
private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Getting Database Account");
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read,
ResourceType.DatabaseAccount, "",
(HashMap<String, String>) null,
null);
return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount);
} catch (Exception e) {
logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Object getSession() {
return this.sessionContainer;
}
public void setSession(Object sessionContainer) {
this.sessionContainer = (SessionContainer) sessionContainer;
}
@Override
public RxClientCollectionCache getCollectionCache() {
return this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return partitionKeyRangeCache;
}
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
return Flux.defer(() -> {
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null);
return this.populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
requestPopulated.setEndpointOverride(endpoint);
return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> {
String message = String.format("Failed to retrieve database account information. %s",
e.getCause() != null
? e.getCause().toString()
: e.toString());
logger.warn(message);
}).map(rsp -> rsp.getResource(DatabaseAccount.class))
.doOnNext(databaseAccount ->
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled()
&& BridgeInternal.isEnableMultipleWriteLocations(databaseAccount));
});
});
}
/**
* Certain requests must be routed through gateway even when the client connectivity mode is direct.
*
* @param request
* @return RxStoreModel
*/
private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) {
if (request.UseGatewayMode) {
return this.gatewayProxy;
}
ResourceType resourceType = request.getResourceType();
OperationType operationType = request.getOperationType();
if (resourceType == ResourceType.Offer ||
resourceType == ResourceType.ClientEncryptionKey ||
resourceType.isScript() && operationType != OperationType.ExecuteJavaScript ||
resourceType == ResourceType.PartitionKeyRange ||
resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) {
return this.gatewayProxy;
}
if (operationType == OperationType.Create
|| operationType == OperationType.Upsert) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection ||
resourceType == ResourceType.Permission) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Delete) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Replace) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Read) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else {
if ((operationType == OperationType.Query ||
operationType == OperationType.SqlQuery ||
operationType == OperationType.ReadFeed) &&
Utils.isCollectionChild(request.getResourceType())) {
if (request.getPartitionKeyRangeIdentity() == null &&
request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) {
return this.gatewayProxy;
}
}
return this.storeModel;
}
}
@Override
public void close() {
logger.info("Attempting to close client {}", this.clientId);
if (!closed.getAndSet(true)) {
activeClientsCnt.decrementAndGet();
logger.info("Shutting down ...");
logger.info("Closing Global Endpoint Manager ...");
LifeCycleUtils.closeQuietly(this.globalEndpointManager);
logger.info("Closing StoreClientFactory ...");
LifeCycleUtils.closeQuietly(this.storeClientFactory);
logger.info("Shutting down reactorHttpClient ...");
LifeCycleUtils.closeQuietly(this.reactorHttpClient);
logger.info("Shutting down CpuMonitor ...");
CpuMemoryMonitor.unregister(this);
if (this.throughputControlEnabled.get()) {
logger.info("Closing ThroughputControlStore ...");
this.throughputControlStore.close();
}
logger.info("Shutting down completed.");
} else {
logger.warn("Already shutdown!");
}
}
@Override
public ItemDeserializer getItemDeserializer() {
return this.itemDeserializer;
}
@Override
public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group can not be null");
if (this.throughputControlEnabled.compareAndSet(false, true)) {
this.throughputControlStore =
new ThroughputControlStore(
this.collectionCache,
this.connectionPolicy.getConnectionMode(),
this.partitionKeyRangeCache);
this.storeModel.enableThroughputControl(throughputControlStore);
}
this.throughputControlStore.enableThroughputControlGroup(group);
}
private static SqlQuerySpec createLogicalPartitionScanQuerySpec(
PartitionKey partitionKey,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE");
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey);
String pkParamName = "@pkValue";
parameters.add(new SqlParameter(pkParamName, pkValue));
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
@Override
public Mono<List<FeedRange>> getFeedRanges(String collectionLink) {
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
collectionLink,
new HashMap<>());
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null);
invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request);
return ObservableHelper.inlineIfPossibleAsObs(
() -> getFeedRangesInternal(request, collectionLink),
invalidPartitionExceptionRetryPolicy);
}
private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) {
logger.debug("getFeedRange collectionLink=[{}]", collectionLink);
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null,
request);
return collectionObs.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache
.tryGetOverlappingRangesAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null);
return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request));
});
}
private static List<FeedRange> toFeedRanges(
Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) {
final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v;
if (partitionKeyRangeList == null) {
request.forceNameCacheRefresh = true;
throw new InvalidPartitionException();
}
List<FeedRange> feedRanges = new ArrayList<>();
partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange)));
return feedRanges;
}
private static FeedRange toFeedRange(PartitionKeyRange pkRange) {
return new FeedRangeEpkImpl(pkRange.toRange());
}
} |
Fixed - also fixed the activeClientCounter (which was never decremented) :-) | public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) {
try {
this.httpClientInterceptor = httpClientInterceptor;
if (httpClientInterceptor != null) {
this.reactorHttpClient = httpClientInterceptor.apply(httpClient());
}
this.gatewayProxy = createRxGatewayProxy(this.sessionContainer,
this.consistencyLevel,
this.queryCompatibilityMode,
this.userAgentContainer,
this.globalEndpointManager,
this.reactorHttpClient,
this.apiType);
this.globalEndpointManager.init();
this.initializeGatewayConfigurationReader();
if (metadataCachesSnapshot != null) {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy,
metadataCachesSnapshot.getCollectionInfoByNameCache(),
metadataCachesSnapshot.getCollectionInfoByIdCache()
);
} else {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy);
}
this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy);
this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this,
collectionCache);
updateGatewayProxy();
clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(),
ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(),
connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(),
null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions());
clientTelemetry.init();
if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) {
this.storeModel = this.gatewayProxy;
} else {
this.initializeDirectConnectivity();
}
this.retryPolicy.setRxCollectionCache(this.collectionCache);
} catch (Exception e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
} | clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(), | public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) {
try {
this.httpClientInterceptor = httpClientInterceptor;
if (httpClientInterceptor != null) {
this.reactorHttpClient = httpClientInterceptor.apply(httpClient());
}
this.gatewayProxy = createRxGatewayProxy(this.sessionContainer,
this.consistencyLevel,
this.queryCompatibilityMode,
this.userAgentContainer,
this.globalEndpointManager,
this.reactorHttpClient,
this.apiType);
this.globalEndpointManager.init();
this.initializeGatewayConfigurationReader();
if (metadataCachesSnapshot != null) {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy,
metadataCachesSnapshot.getCollectionInfoByNameCache(),
metadataCachesSnapshot.getCollectionInfoByIdCache()
);
} else {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy);
}
this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy);
this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this,
collectionCache);
updateGatewayProxy();
clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(),
ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(),
connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(),
null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions());
clientTelemetry.init();
if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) {
this.storeModel = this.gatewayProxy;
} else {
this.initializeDirectConnectivity();
}
this.retryPolicy.setRxCollectionCache(this.collectionCache);
} catch (Exception e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
} | class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener,
DiagnosticsClientContext {
private static final String tempMachineId = "uuid:" + UUID.randomUUID();
private static final AtomicInteger activeClientsCnt = new AtomicInteger(0);
private static final AtomicInteger clientIdGenerator = new AtomicInteger(0);
private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>(
PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey,
PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false);
private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " +
"ParallelDocumentQueryExecutioncontext, but not used";
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper();
private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer();
private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class);
private final String masterKeyOrResourceToken;
private final URI serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel consistencyLevel;
private final BaseAuthorizationTokenProvider authorizationTokenProvider;
private final UserAgentContainer userAgentContainer;
private final boolean hasAuthKeyResourceToken;
private final Configs configs;
private final boolean connectionSharingAcrossClientsEnabled;
private AzureKeyCredential credential;
private final TokenCredential tokenCredential;
private String[] tokenCredentialScopes;
private SimpleTokenCache tokenCredentialCache;
private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver;
AuthorizationTokenType authorizationTokenType;
private SessionContainer sessionContainer;
private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY;
private RxClientCollectionCache collectionCache;
private RxStoreModel gatewayProxy;
private RxStoreModel storeModel;
private GlobalAddressResolver addressResolver;
private RxPartitionKeyRangeCache partitionKeyRangeCache;
private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap;
private final boolean contentResponseOnWriteEnabled;
private Map<String, PartitionedQueryExecutionInfo> queryPlanCache;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final int clientId;
private ClientTelemetry clientTelemetry;
private ApiType apiType;
private IRetryPolicyFactory resetSessionTokenRetryPolicy;
/**
* Compatibility mode: Allows to specify compatibility mode used by client when
* making query requests. Should be removed when application/sql is no longer
* supported.
*/
private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default;
private final GlobalEndpointManager globalEndpointManager;
private final RetryPolicy retryPolicy;
private HttpClient reactorHttpClient;
private Function<HttpClient, HttpClient> httpClientInterceptor;
private volatile boolean useMultipleWriteLocations;
private StoreClientFactory storeClientFactory;
private GatewayServiceConfigurationReader gatewayConfigurationReader;
private final DiagnosticsClientConfig diagnosticsClientConfig;
private final AtomicBoolean throughputControlEnabled;
private ThroughputControlStore throughputControlStore;
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
private RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
if (permissionFeed != null && permissionFeed.size() > 0) {
this.resourceTokensMap = new HashMap<>();
for (Permission permission : permissionFeed) {
String[] segments = StringUtils.split(permission.getResourceLink(),
Constants.Properties.PATH_SEPARATOR.charAt(0));
if (segments.length <= 0) {
throw new IllegalArgumentException("resourceLink");
}
List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null;
PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false);
if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) {
throw new IllegalArgumentException(permission.getResourceLink());
}
partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName);
if (partitionKeyAndResourceTokenPairs == null) {
partitionKeyAndResourceTokenPairs = new ArrayList<>();
this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs);
}
PartitionKey partitionKey = permission.getResourcePartitionKey();
partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair(
partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty,
permission.getToken()));
logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]",
pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken());
}
if(this.resourceTokensMap.isEmpty()) {
throw new IllegalArgumentException("permissionFeed");
}
String firstToken = permissionFeed.get(0).getToken();
if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) {
this.firstResourceTokenFromPermissionFeed = firstToken;
}
}
}
RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
activeClientsCnt.incrementAndGet();
this.clientId = clientIdGenerator.getAndDecrement();
this.diagnosticsClientConfig = new DiagnosticsClientConfig();
this.diagnosticsClientConfig.withClientId(this.clientId);
this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt);
this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled);
this.diagnosticsClientConfig.withConsistency(consistencyLevel);
this.throughputControlEnabled = new AtomicBoolean(false);
logger.info(
"Initializing DocumentClient [{}] with"
+ " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]",
this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol());
try {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
this.configs = configs;
this.masterKeyOrResourceToken = masterKeyOrResourceToken;
this.serviceEndpoint = serviceEndpoint;
this.credential = credential;
this.tokenCredential = tokenCredential;
this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled;
this.authorizationTokenType = AuthorizationTokenType.Invalid;
if (this.credential != null) {
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.authorizationTokenProvider = null;
hasAuthKeyResourceToken = true;
this.authorizationTokenType = AuthorizationTokenType.ResourceToken;
} else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken);
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else {
hasAuthKeyResourceToken = false;
this.authorizationTokenProvider = null;
if (tokenCredential != null) {
this.tokenCredentialScopes = new String[] {
serviceEndpoint.getScheme() + ":
};
this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential
.getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes)));
this.authorizationTokenType = AuthorizationTokenType.AadToken;
}
}
if (connectionPolicy != null) {
this.connectionPolicy = connectionPolicy;
} else {
this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig());
}
this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode());
this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled());
this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled());
this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions());
this.diagnosticsClientConfig.withMachineId(tempMachineId);
boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled);
this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing);
this.consistencyLevel = consistencyLevel;
this.userAgentContainer = new UserAgentContainer();
String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix();
if (userAgentSuffix != null && userAgentSuffix.length() > 0) {
userAgentContainer.setSuffix(userAgentSuffix);
}
this.httpClientInterceptor = null;
this.reactorHttpClient = httpClient();
this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs);
this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy);
this.resetSessionTokenRetryPolicy = retryPolicy;
CpuMemoryMonitor.register(this);
this.queryPlanCache = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE));
this.apiType = apiType;
} catch (RuntimeException e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
}
@Override
public DiagnosticsClientConfig getConfig() {
return diagnosticsClientConfig;
}
@Override
public CosmosDiagnostics createDiagnostics() {
return BridgeInternal.createCosmosDiagnostics(this, this.globalEndpointManager);
}
private void initializeGatewayConfigurationReader() {
this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager);
DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount();
if (databaseAccount == null) {
logger.error("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
throw new RuntimeException("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
}
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount);
}
private void updateGatewayProxy() {
((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader);
((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache);
((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache);
((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations);
}
public void serialize(CosmosClientMetadataCachesSnapshot state) {
RxCollectionCache.serialize(state, this.collectionCache);
}
private void initializeDirectConnectivity() {
this.addressResolver = new GlobalAddressResolver(this,
this.reactorHttpClient,
this.globalEndpointManager,
this.configs.getProtocol(),
this,
this.collectionCache,
this.partitionKeyRangeCache,
userAgentContainer,
null,
this.connectionPolicy,
this.apiType);
this.storeClientFactory = new StoreClientFactory(
this.addressResolver,
this.diagnosticsClientConfig,
this.configs,
this.connectionPolicy,
this.userAgentContainer,
this.connectionSharingAcrossClientsEnabled,
this.clientTelemetry
);
this.createStoreModel(true);
}
DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() {
return new DatabaseAccountManagerInternal() {
@Override
public URI getServiceEndpoint() {
return RxDocumentClientImpl.this.getServiceEndpoint();
}
@Override
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
logger.info("Getting database account endpoint from {}", endpoint);
return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return RxDocumentClientImpl.this.getConnectionPolicy();
}
};
}
RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer,
ConsistencyLevel consistencyLevel,
QueryCompatibilityMode queryCompatibilityMode,
UserAgentContainer userAgentContainer,
GlobalEndpointManager globalEndpointManager,
HttpClient httpClient,
ApiType apiType) {
return new RxGatewayStoreModel(
this,
sessionContainer,
consistencyLevel,
queryCompatibilityMode,
userAgentContainer,
globalEndpointManager,
httpClient,
apiType);
}
private HttpClient httpClient() {
HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs)
.withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout())
.withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize())
.withProxy(this.connectionPolicy.getProxy())
.withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout());
if (connectionSharingAcrossClientsEnabled) {
return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig);
} else {
diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig);
return HttpClient.createFixed(httpClientConfig);
}
}
private void createStoreModel(boolean subscribeRntbdStatus) {
StoreClient storeClient = this.storeClientFactory.createStoreClient(this,
this.addressResolver,
this.sessionContainer,
this.gatewayConfigurationReader,
this,
this.useMultipleWriteLocations
);
this.storeModel = new ServerStoreModel(storeClient);
}
@Override
public URI getServiceEndpoint() {
return this.serviceEndpoint;
}
@Override
public URI getWriteEndpoint() {
return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null);
}
@Override
public URI getReadEndpoint() {
return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return this.connectionPolicy;
}
@Override
public boolean isContentResponseOnWriteEnabled() {
return contentResponseOnWriteEnabled;
}
@Override
public ConsistencyLevel getConsistencyLevel() {
return consistencyLevel;
}
@Override
public ClientTelemetry getClientTelemetry() {
return this.clientTelemetry;
}
@Override
public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (database == null) {
throw new IllegalArgumentException("Database");
}
logger.debug("Creating a Database. id: [{}]", database.getId());
validateResource(database);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Reading a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT);
}
private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) {
switch (resourceTypeEnum) {
case Database:
return Paths.DATABASES_ROOT;
case DocumentCollection:
return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT);
case Document:
return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT);
case Offer:
return Paths.OFFERS_ROOT;
case User:
return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT);
case ClientEncryptionKey:
return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
case Permission:
return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT);
case Attachment:
return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT);
case StoredProcedure:
return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
case Trigger:
return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT);
case UserDefinedFunction:
return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
case Conflict:
return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT);
default:
throw new IllegalArgumentException("resource type not supported");
}
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) {
if (options == null) {
return null;
}
return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options);
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) {
if (options == null) {
return null;
}
return options.getOperationContextAndListenerTuple();
}
private <T extends Resource> Flux<FeedResponse<T>> createQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum) {
String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum);
UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getCorrelationActivityId(options);
UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ?
correlationActivityIdOfRequestOptions : Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this,
getOperationContextAndListenerTuple(options));
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> createQueryInternal(
resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId),
invalidPartitionExceptionRetryPolicy);
}
private <T extends Resource> Flux<FeedResponse<T>> createQueryInternal(
String resourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
IDocumentQueryClient queryClient,
UUID activityId) {
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory
.createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery,
options, resourceLink, false, activityId,
Configs.isQueryPlanCachingEnabled(), queryPlanCache);
AtomicBoolean isFirstResponse = new AtomicBoolean(true);
return executionContext.flatMap(iDocumentQueryExecutionContext -> {
QueryInfo queryInfo = null;
if (iDocumentQueryExecutionContext instanceof PipelinedDocumentQueryExecutionContext) {
queryInfo = ((PipelinedDocumentQueryExecutionContext<T>) iDocumentQueryExecutionContext).getQueryInfo();
}
QueryInfo finalQueryInfo = queryInfo;
return iDocumentQueryExecutionContext.executeAsync()
.map(tFeedResponse -> {
if (finalQueryInfo != null) {
if (finalQueryInfo.hasSelectValue()) {
ModelBridgeInternal
.addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo);
}
if (isFirstResponse.compareAndSet(true, false)) {
ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse,
finalQueryInfo.getQueryPlanDiagnosticsContext());
}
}
return tFeedResponse;
});
});
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) {
return queryDatabases(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database);
}
@Override
public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink,
DocumentCollection collection, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink,
DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink,
collection.getId());
validateResource(collection);
String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
});
} catch (Exception e) {
logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Replacing a Collection. id: [{}]", collection.getId());
validateResource(collection);
String path = Utils.joinPath(collection.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
if (resourceResponse.getResource() != null) {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
}
});
} catch (Exception e) {
logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.DELETE)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated));
}
private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated ->
this.getStoreProxy(requestPopulated).processMessage(requestPopulated)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
));
}
@Override
public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class,
Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection);
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection);
}
private static String serializeProcedureParams(List<Object> objectArray) {
String[] stringArray = new String[objectArray.size()];
for (int i = 0; i < objectArray.size(); ++i) {
Object object = objectArray.get(i);
if (object instanceof JsonSerializable) {
stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object);
} else {
try {
stringArray[i] = mapper.writeValueAsString(object);
} catch (IOException e) {
throw new IllegalArgumentException("Can't serialize the object into the json string", e);
}
}
}
return String.format("[%s]", StringUtils.join(stringArray, ","));
}
private static void validateResource(Resource resource) {
if (!StringUtils.isEmpty(resource.getId())) {
if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 ||
resource.getId().indexOf('?') != -1 || resource.getId().indexOf('
throw new IllegalArgumentException("Id contains illegal chars.");
}
if (resource.getId().endsWith(" ")) {
throw new IllegalArgumentException("Id ends with a space.");
}
}
}
private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) {
Map<String, String> headers = new HashMap<>();
if (this.useMultipleWriteLocations) {
headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString());
}
if (consistencyLevel != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString());
}
if (options == null) {
if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
return headers;
}
Map<String, String> customOptions = options.getHeaders();
if (customOptions != null) {
headers.putAll(customOptions);
}
boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled;
if (options.isContentResponseOnWriteEnabled() != null) {
contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled();
}
if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
if (options.getIfMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag());
}
if(options.getIfNoneMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag());
}
if (options.getConsistencyLevel() != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString());
}
if (options.getIndexingDirective() != null) {
headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString());
}
if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) {
String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude);
}
if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) {
String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude);
}
if (!Strings.isNullOrEmpty(options.getSessionToken())) {
headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken());
}
if (options.getResourceTokenExpirySeconds() != null) {
headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY,
String.valueOf(options.getResourceTokenExpirySeconds()));
}
if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString());
} else if (options.getOfferType() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType());
}
if (options.getOfferThroughput() == null) {
if (options.getThroughputProperties() != null) {
Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties());
final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings();
OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null;
if (offerAutoscaleSettings != null) {
autoscaleAutoUpgradeProperties
= offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties();
}
if (offer.hasOfferThroughput() &&
(offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 ||
autoscaleAutoUpgradeProperties != null &&
autoscaleAutoUpgradeProperties
.getAutoscaleThroughputProperties()
.getIncrementPercent() >= 0)) {
throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with "
+ "fixed offer");
}
if (offer.hasOfferThroughput()) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput()));
} else if (offer.getOfferAutoScaleSettings() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS,
ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings()));
}
}
}
if (options.isQuotaInfoEnabled()) {
headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true));
}
if (options.isScriptLoggingEnabled()) {
headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true));
}
if (options.getDedicatedGatewayRequestOptions() != null &&
options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) {
headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS,
String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions())));
}
return headers;
}
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return this.resetSessionTokenRetryPolicy;
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Document document,
RequestOptions options) {
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs
.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object document,
RequestOptions options,
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) {
return collectionObs.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private void addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object objectDoc, RequestOptions options,
DocumentCollection collection) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
PartitionKeyInternal partitionKeyInternal = null;
if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else if (options != null && options.getPartitionKey() != null) {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey());
} else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) {
partitionKeyInternal = PartitionKeyInternal.getEmpty();
} else if (contentAsByteBuffer != null || objectDoc != null) {
InternalObjectNode internalObjectNode;
if (objectDoc instanceof InternalObjectNode) {
internalObjectNode = (InternalObjectNode) objectDoc;
} else if (objectDoc instanceof ObjectNode) {
internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc);
} else if (contentAsByteBuffer != null) {
contentAsByteBuffer.rewind();
internalObjectNode = new InternalObjectNode(contentAsByteBuffer);
} else {
throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null");
}
Instant serializationStartTime = Instant.now();
partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTime,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION
);
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
} else {
throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation.");
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
}
public static PartitionKeyInternal extractPartitionKeyValueFromDocument(
InternalObjectNode document,
PartitionKeyDefinition partitionKeyDefinition) {
if (partitionKeyDefinition != null) {
switch (partitionKeyDefinition.getKind()) {
case HASH:
String path = partitionKeyDefinition.getPaths().iterator().next();
List<String> parts = PathParser.getPathParts(path);
if (parts.size() >= 1) {
Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts);
if (value == null || value.getClass() == ObjectNode.class) {
value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
}
if (value instanceof PartitionKeyInternal) {
return (PartitionKeyInternal) value;
} else {
return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false);
}
}
break;
case MULTI_HASH:
Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()];
for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){
String partitionPath = partitionKeyDefinition.getPaths().get(pathIter);
List<String> partitionPathParts = PathParser.getPathParts(partitionPath);
partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts);
}
return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false);
default:
throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind());
}
}
return null;
}
private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
Object document,
RequestOptions options,
boolean disableAutomaticIdGeneration,
OperationType operationType) {
if (StringUtils.isEmpty(documentCollectionLink)) {
throw new IllegalArgumentException("documentCollectionLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Document, path, requestHeaders, options, content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return addPartitionKeyInformation(request, content, document, options, collectionObs);
}
private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink");
checkNotNull(serverBatchRequest, "expected non null serverBatchRequest");
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody()));
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Batch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> {
addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v);
return request;
});
}
private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request,
ServerBatchRequest serverBatchRequest,
DocumentCollection collection) {
if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) {
PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue();
PartitionKeyInternal partitionKeyInternal;
if (partitionKey.equals(PartitionKey.NONE)) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey);
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
} else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) {
request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId()));
} else {
throw new UnsupportedOperationException("Unknown Server request.");
}
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString());
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch()));
request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError()));
request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size());
return request;
}
private Mono<RxDocumentServiceRequest> populateHeaders(RxDocumentServiceRequest request, RequestVerb httpMethod) {
request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123());
if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null
|| this.cosmosAuthorizationTokenResolver != null || this.credential != null) {
String resourceName = request.getResourceAddress();
String authorization = this.getUserAuthorizationToken(
resourceName, request.getResourceType(), httpMethod, request.getHeaders(),
AuthorizationTokenType.PrimaryMasterKey, request.properties);
try {
authorization = URLEncoder.encode(authorization, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Failed to encode authtoken.", e);
}
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
}
if (this.apiType != null) {
request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString());
}
if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod))
&& !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
}
if (RequestVerb.PATCH.equals(httpMethod) &&
!request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH);
}
if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) {
request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
}
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
if (this.requiresFeedRangeFiltering(request)) {
return request.getFeedRange()
.populateFeedRangeFilteringHeaders(
this.getPartitionKeyRangeCache(),
request,
this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request))
.flatMap(this::populateAuthorizationHeader);
}
return this.populateAuthorizationHeader(request);
}
private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) {
if (request.getResourceType() != ResourceType.Document &&
request.getResourceType() != ResourceType.Conflict) {
return false;
}
switch (request.getOperationType()) {
case ReadFeed:
case Query:
case SqlQuery:
return request.getFeedRange() != null;
default:
return false;
}
}
@Override
public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) {
if (request == null) {
throw new IllegalArgumentException("request");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return request;
});
} else {
return Mono.just(request);
}
}
@Override
public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) {
if (httpHeaders == null) {
throw new IllegalArgumentException("httpHeaders");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return httpHeaders;
});
}
return Mono.just(httpHeaders);
}
@Override
public AuthorizationTokenType getAuthorizationTokenType() {
return this.authorizationTokenType;
}
@Override
public String getUserAuthorizationToken(String resourceName,
ResourceType resourceType,
RequestVerb requestVerb,
Map<String, String> headers,
AuthorizationTokenType tokenType,
Map<String, Object> properties) {
if (this.cosmosAuthorizationTokenResolver != null) {
return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(),
properties != null ? Collections.unmodifiableMap(properties) : null);
} else if (credential != null) {
return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName,
resourceType, headers);
} else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) {
return masterKeyOrResourceToken;
} else {
assert resourceTokensMap != null;
if(resourceType.equals(ResourceType.DatabaseAccount)) {
return this.firstResourceTokenFromPermissionFeed;
}
return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers);
}
}
private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) {
CosmosResourceType cosmosResourceType =
ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString());
if (cosmosResourceType == null) {
return CosmosResourceType.SYSTEM;
}
return cosmosResourceType;
}
void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) {
this.sessionContainer.setSessionToken(request, response.getResponseHeaders());
}
private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
Map<String, String> headers = requestPopulated.getHeaders();
assert (headers != null);
headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true");
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
);
});
}
private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.PUT)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PATCH);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(request).processMessage(request);
}
@Override
public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) {
try {
logger.debug("Creating a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Create);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance);
}
private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Upsert);
Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = Utils.getCollectionName(documentLink);
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Document typedDocument = documentFromObject(document, mapper);
return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = document.getSelfLink();
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (document == null) {
throw new IllegalArgumentException("document");
}
return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a database due to [{}]", e.getMessage());
return Mono.error(e);
}
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink,
Document document,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
if (document == null) {
throw new IllegalArgumentException("document");
}
logger.debug("Replacing a Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = serializeJsonToByteBuffer(document);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs);
return requestObs.flatMap(req -> replace(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> patchDocument(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink");
checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations");
logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options));
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Patch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(
request,
null,
null,
options,
collectionObs);
return requestObs.flatMap(req -> patch(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy);
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Deleting a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs);
return requestObs.flatMap(req -> this
.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> this
.deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting documents due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Reading a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> {
return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Document>> readDocuments(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return queryDocuments(collectionLink, "SELECT * FROM r", options);
}
@Override
public <T> Mono<FeedResponse<T>> readMany(
List<CosmosItemIdentity> itemIdentityList,
String collectionLink,
CosmosQueryRequestOptions options,
Class<T> klass) {
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink, null
);
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request);
return collectionObs
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache
.tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null);
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap =
new HashMap<>();
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
itemIdentityList
.forEach(itemIdentity -> {
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(
itemIdentity.getPartitionKey()),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
if (partitionRangeItemKeyMap.get(range) == null) {
List<CosmosItemIdentity> list = new ArrayList<>();
list.add(itemIdentity);
partitionRangeItemKeyMap.put(range, list);
} else {
List<CosmosItemIdentity> pairs =
partitionRangeItemKeyMap.get(range);
pairs.add(itemIdentity);
partitionRangeItemKeyMap.put(range, pairs);
}
});
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap;
rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap,
collection.getPartitionKey());
return createReadManyQuery(
resourceLink,
new SqlQuerySpec(DUMMY_SQL_QUERY),
options,
Document.class,
ResourceType.Document,
collection,
Collections.unmodifiableMap(rangeQueryMap))
.collectList()
.map(feedList -> {
List<T> finalList = new ArrayList<>();
HashMap<String, String> headers = new HashMap<>();
ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>();
double requestCharge = 0;
for (FeedResponse<Document> page : feedList) {
ConcurrentMap<String, QueryMetrics> pageQueryMetrics =
ModelBridgeInternal.queryMetrics(page);
if (pageQueryMetrics != null) {
pageQueryMetrics.forEach(
aggregatedQueryMetrics::putIfAbsent);
}
requestCharge += page.getRequestCharge();
finalList.addAll(page.getResults().stream().map(document ->
ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList()));
}
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double
.toString(requestCharge));
FeedResponse<T> frp = BridgeInternal
.createFeedResponse(finalList, headers);
return frp;
});
});
}
);
}
private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap(
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap,
PartitionKeyDefinition partitionKeyDefinition) {
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>();
String partitionKeySelector = createPkSelector(partitionKeyDefinition);
for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) {
SqlQuerySpec sqlQuerySpec;
if (partitionKeySelector.equals("[\"id\"]")) {
sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector);
} else {
sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector);
}
rangeQueryMap.put(entry.getKey(), sqlQuerySpec);
}
return rangeQueryMap;
}
private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(
List<CosmosItemIdentity> idPartitionKeyPairList,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( ");
for (int i = 0; i < idPartitionKeyPairList.size(); i++) {
CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i);
String idValue = itemIdentity.getId();
String idParamName = "@param" + i;
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
if (!Objects.equals(idValue, pkValue)) {
continue;
}
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append(idParamName);
if (i < idPartitionKeyPairList.size() - 1) {
queryStringBuilder.append(", ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE ( ");
for (int i = 0; i < itemIdentities.size(); i++) {
CosmosItemIdentity itemIdentity = itemIdentities.get(i);
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
String pkParamName = "@param" + (2 * i);
parameters.add(new SqlParameter(pkParamName, pkValue));
String idValue = itemIdentity.getId();
String idParamName = "@param" + (2 * i + 1);
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append("(");
queryStringBuilder.append("c.id = ");
queryStringBuilder.append(idParamName);
queryStringBuilder.append(" AND ");
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
queryStringBuilder.append(" )");
if (i < itemIdentities.size() - 1) {
queryStringBuilder.append(" OR ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) {
return partitionKeyDefinition.getPaths()
.stream()
.map(pathPart -> StringUtils.substring(pathPart, 1))
.map(pathPart -> StringUtils.replace(pathPart, "\"", "\\"))
.map(part -> "[\"" + part + "\"]")
.collect(Collectors.joining());
}
private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
DocumentCollection collection,
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) {
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(),
sqlQuery,
rangeQueryMap,
options,
collection.getResourceId(),
parentResourceLink,
activityId,
klass,
resourceTypeEnum);
return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync);
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, String query, CosmosQueryRequestOptions options) {
return queryDocuments(collectionLink, new SqlQuerySpec(query), options);
}
private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return new IDocumentQueryClient () {
@Override
public RxCollectionCache getCollectionCache() {
return RxDocumentClientImpl.this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return RxDocumentClientImpl.this.partitionKeyRangeCache;
}
@Override
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy;
}
@Override
public ConsistencyLevel getDefaultConsistencyLevelAsync() {
return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel();
}
@Override
public ConsistencyLevel getDesiredConsistencyLevelAsync() {
return RxDocumentClientImpl.this.consistencyLevel;
}
@Override
public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) {
if (operationContextAndListenerTuple == null) {
return RxDocumentClientImpl.this.query(request).single();
} else {
final OperationListener listener =
operationContextAndListenerTuple.getOperationListener();
final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext();
request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId());
listener.requestListener(operationContext, request);
return RxDocumentClientImpl.this.query(request).single().doOnNext(
response -> listener.responseListener(operationContext, response)
).doOnError(
ex -> listener.exceptionListener(operationContext, ex)
);
}
}
@Override
public QueryCompatibilityMode getQueryCompatibilityMode() {
return QueryCompatibilityMode.Default;
}
@Override
public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) {
return null;
}
};
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
SqlQuerySpecLogger.getInstance().logQuery(querySpec);
return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document);
}
@Override
public Flux<FeedResponse<Document>> queryDocumentChangeFeed(
final DocumentCollection collection,
final CosmosChangeFeedRequestOptions changeFeedOptions) {
checkNotNull(collection, "Argument 'collection' must not be null.");
ChangeFeedQueryImpl<Document> changeFeedQueryImpl = new ChangeFeedQueryImpl<>(
this,
ResourceType.Document,
Document.class,
collection.getAltLink(),
collection.getResourceId(),
changeFeedOptions);
return changeFeedQueryImpl.executeAsync();
}
@Override
public Flux<FeedResponse<Document>> readAllDocuments(
String collectionLink,
PartitionKey partitionKey,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (partitionKey == null) {
throw new IllegalArgumentException("partitionKey");
}
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null
);
Flux<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request).flux();
return collectionObs.flatMap(documentCollectionResourceResponse -> {
DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
String pkSelector = createPkSelector(pkDefinition);
SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector);
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
final CosmosQueryRequestOptions effectiveOptions =
ModelBridgeInternal.createQueryRequestOptions(options);
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> {
Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache
.tryLookupAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null).flux();
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(partitionKey),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
return createQueryInternal(
resourceLink,
querySpec,
ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()),
Document.class,
ResourceType.Document,
queryClient,
activityId);
});
},
invalidPartitionExceptionRetryPolicy);
});
}
@Override
public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() {
return queryPlanCache;
}
@Override
public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class,
Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT));
}
private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
validateResource(storedProcedure);
String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType,
ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
return request;
}
private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (udf == null) {
throw new IllegalArgumentException("udf");
}
validateResource(udf);
String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Create);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId());
RxDocumentClientImpl.validateResource(storedProcedure);
String path = Utils.joinPath(storedProcedure.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class,
Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
List<Object> procedureParams) {
return this.executeStoredProcedure(storedProcedureLink, null, procedureParams);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy);
}
@Override
public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy);
}
private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) {
try {
logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript);
requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ExecuteJavaScript,
ResourceType.StoredProcedure, path,
procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "",
requestHeaders, options);
if (retryPolicy != null) {
retryPolicy.onBeforeSendRequest(request);
}
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options))
.map(response -> {
this.captureSessionToken(request, response);
return toStoredProcedureResponse(response);
}));
} catch (Exception e) {
logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
DocumentClientRetryPolicy requestRetryPolicy,
boolean disableAutomaticIdGeneration) {
try {
logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size());
Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true));
} catch (Exception ex) {
logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex);
return Mono.error(ex);
}
}
@Override
public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path,
trigger, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId());
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(trigger.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Trigger, Trigger.class,
Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryTriggers(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger);
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (udf == null) {
throw new IllegalArgumentException("udf");
}
logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId());
validateResource(udf);
String path = Utils.joinPath(udf.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class,
Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
String query, CosmosQueryRequestOptions options) {
return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction);
}
@Override
public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Conflict, Conflict.class,
Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryConflicts(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict);
}
@Override
public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (user == null) {
throw new IllegalArgumentException("user");
}
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.User, path, user, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (user == null) {
throw new IllegalArgumentException("user");
}
logger.debug("Replacing a User. user id [{}]", user.getId());
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(user.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.User, path, user, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Deleting a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Reading a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.User, User.class,
Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) {
return queryUsers(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User);
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(clientEncryptionKeyLink)) {
throw new IllegalArgumentException("clientEncryptionKeyLink");
}
logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink);
String path = Utils.joinPath(clientEncryptionKeyLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink,
ClientEncryptionKey clientEncryptionKey, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId());
RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey,
String nameBasedLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey,
nameBasedLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId());
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(nameBasedLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey,
OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders,
options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class,
Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey);
}
@Override
public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy());
}
private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
if (permission == null) {
throw new IllegalArgumentException("permission");
}
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Permission, path, permission, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (permission == null) {
throw new IllegalArgumentException("permission");
}
logger.debug("Replacing a Permission. permission id [{}]", permission.getId());
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(permission.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Reading a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
return readFeed(options, ResourceType.Permission, Permission.class,
Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query,
CosmosQueryRequestOptions options) {
return queryPermissions(userLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission);
}
@Override
public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
if (offer == null) {
throw new IllegalArgumentException("offer");
}
logger.debug("Replacing an Offer. offer id [{}]", offer.getId());
RxDocumentClientImpl.validateResource(offer);
String path = Utils.joinPath(offer.getSelfLink(), null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace,
ResourceType.Offer, path, offer, null, null);
return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Offer>> readOffer(String offerLink) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(offerLink)) {
throw new IllegalArgumentException("offerLink");
}
logger.debug("Reading an Offer. offerLink [{}]", offerLink);
String path = Utils.joinPath(offerLink, null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Offer, Offer.class,
Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null));
}
private <T extends Resource> Flux<FeedResponse<T>> readFeed(CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options);
int maxPageSize = maxItemCount != null ? maxItemCount : -1;
final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options;
DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> {
Map<String, String> requestHeaders = new HashMap<>();
if (continuationToken != null) {
requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken);
}
requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize));
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions);
retryPolicy.onBeforeSendRequest(request);
return request;
};
Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper
.inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)),
retryPolicy);
return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, maxPageSize);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) {
return queryOffers(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer);
}
@Override
public Mono<DatabaseAccount> getDatabaseAccount() {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy),
documentClientRetryPolicy);
}
@Override
public DatabaseAccount getLatestDatabaseAccount() {
return this.globalEndpointManager.getLatestDatabaseAccount();
}
private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Getting Database Account");
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read,
ResourceType.DatabaseAccount, "",
(HashMap<String, String>) null,
null);
return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount);
} catch (Exception e) {
logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Object getSession() {
return this.sessionContainer;
}
public void setSession(Object sessionContainer) {
this.sessionContainer = (SessionContainer) sessionContainer;
}
@Override
public RxClientCollectionCache getCollectionCache() {
return this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return partitionKeyRangeCache;
}
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
return Flux.defer(() -> {
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null);
return this.populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
requestPopulated.setEndpointOverride(endpoint);
return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> {
String message = String.format("Failed to retrieve database account information. %s",
e.getCause() != null
? e.getCause().toString()
: e.toString());
logger.warn(message);
}).map(rsp -> rsp.getResource(DatabaseAccount.class))
.doOnNext(databaseAccount ->
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled()
&& BridgeInternal.isEnableMultipleWriteLocations(databaseAccount));
});
});
}
/**
* Certain requests must be routed through gateway even when the client connectivity mode is direct.
*
* @param request
* @return RxStoreModel
*/
private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) {
if (request.UseGatewayMode) {
return this.gatewayProxy;
}
ResourceType resourceType = request.getResourceType();
OperationType operationType = request.getOperationType();
if (resourceType == ResourceType.Offer ||
resourceType == ResourceType.ClientEncryptionKey ||
resourceType.isScript() && operationType != OperationType.ExecuteJavaScript ||
resourceType == ResourceType.PartitionKeyRange ||
resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) {
return this.gatewayProxy;
}
if (operationType == OperationType.Create
|| operationType == OperationType.Upsert) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection ||
resourceType == ResourceType.Permission) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Delete) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Replace) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Read) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else {
if ((operationType == OperationType.Query ||
operationType == OperationType.SqlQuery ||
operationType == OperationType.ReadFeed) &&
Utils.isCollectionChild(request.getResourceType())) {
if (request.getPartitionKeyRangeIdentity() == null &&
request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) {
return this.gatewayProxy;
}
}
return this.storeModel;
}
}
@Override
public void close() {
logger.info("Attempting to close client {}", this.clientId);
if (!closed.getAndSet(true)) {
logger.info("Shutting down ...");
logger.info("Closing Global Endpoint Manager ...");
LifeCycleUtils.closeQuietly(this.globalEndpointManager);
logger.info("Closing StoreClientFactory ...");
LifeCycleUtils.closeQuietly(this.storeClientFactory);
logger.info("Shutting down reactorHttpClient ...");
LifeCycleUtils.closeQuietly(this.reactorHttpClient);
logger.info("Shutting down CpuMonitor ...");
CpuMemoryMonitor.unregister(this);
if (this.throughputControlEnabled.get()) {
logger.info("Closing ThroughputControlStore ...");
this.throughputControlStore.close();
}
logger.info("Shutting down completed.");
} else {
logger.warn("Already shutdown!");
}
}
@Override
public ItemDeserializer getItemDeserializer() {
return this.itemDeserializer;
}
@Override
public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group can not be null");
if (this.throughputControlEnabled.compareAndSet(false, true)) {
this.throughputControlStore =
new ThroughputControlStore(
this.collectionCache,
this.connectionPolicy.getConnectionMode(),
this.partitionKeyRangeCache);
this.storeModel.enableThroughputControl(throughputControlStore);
}
this.throughputControlStore.enableThroughputControlGroup(group);
}
private static SqlQuerySpec createLogicalPartitionScanQuerySpec(
PartitionKey partitionKey,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE");
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey);
String pkParamName = "@pkValue";
parameters.add(new SqlParameter(pkParamName, pkValue));
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
@Override
public Mono<List<FeedRange>> getFeedRanges(String collectionLink) {
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
collectionLink,
new HashMap<>());
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null);
invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request);
return ObservableHelper.inlineIfPossibleAsObs(
() -> getFeedRangesInternal(request, collectionLink),
invalidPartitionExceptionRetryPolicy);
}
private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) {
logger.debug("getFeedRange collectionLink=[{}]", collectionLink);
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null,
request);
return collectionObs.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache
.tryGetOverlappingRangesAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null);
return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request));
});
}
private static List<FeedRange> toFeedRanges(
Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) {
final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v;
if (partitionKeyRangeList == null) {
request.forceNameCacheRefresh = true;
throw new InvalidPartitionException();
}
List<FeedRange> feedRanges = new ArrayList<>();
partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange)));
return feedRanges;
}
private static FeedRange toFeedRange(PartitionKeyRange pkRange) {
return new FeedRangeEpkImpl(pkRange.toRange());
}
} | class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener,
DiagnosticsClientContext {
private static final String tempMachineId = "uuid:" + UUID.randomUUID();
private static final AtomicInteger activeClientsCnt = new AtomicInteger(0);
private static final AtomicInteger clientIdGenerator = new AtomicInteger(0);
private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>(
PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey,
PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false);
private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " +
"ParallelDocumentQueryExecutioncontext, but not used";
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper();
private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer();
private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class);
private final String masterKeyOrResourceToken;
private final URI serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel consistencyLevel;
private final BaseAuthorizationTokenProvider authorizationTokenProvider;
private final UserAgentContainer userAgentContainer;
private final boolean hasAuthKeyResourceToken;
private final Configs configs;
private final boolean connectionSharingAcrossClientsEnabled;
private AzureKeyCredential credential;
private final TokenCredential tokenCredential;
private String[] tokenCredentialScopes;
private SimpleTokenCache tokenCredentialCache;
private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver;
AuthorizationTokenType authorizationTokenType;
private SessionContainer sessionContainer;
private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY;
private RxClientCollectionCache collectionCache;
private RxStoreModel gatewayProxy;
private RxStoreModel storeModel;
private GlobalAddressResolver addressResolver;
private RxPartitionKeyRangeCache partitionKeyRangeCache;
private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap;
private final boolean contentResponseOnWriteEnabled;
private Map<String, PartitionedQueryExecutionInfo> queryPlanCache;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final int clientId;
private ClientTelemetry clientTelemetry;
private ApiType apiType;
private IRetryPolicyFactory resetSessionTokenRetryPolicy;
/**
* Compatibility mode: Allows to specify compatibility mode used by client when
* making query requests. Should be removed when application/sql is no longer
* supported.
*/
private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default;
private final GlobalEndpointManager globalEndpointManager;
private final RetryPolicy retryPolicy;
private HttpClient reactorHttpClient;
private Function<HttpClient, HttpClient> httpClientInterceptor;
private volatile boolean useMultipleWriteLocations;
private StoreClientFactory storeClientFactory;
private GatewayServiceConfigurationReader gatewayConfigurationReader;
private final DiagnosticsClientConfig diagnosticsClientConfig;
private final AtomicBoolean throughputControlEnabled;
private ThroughputControlStore throughputControlStore;
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
private RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
if (permissionFeed != null && permissionFeed.size() > 0) {
this.resourceTokensMap = new HashMap<>();
for (Permission permission : permissionFeed) {
String[] segments = StringUtils.split(permission.getResourceLink(),
Constants.Properties.PATH_SEPARATOR.charAt(0));
if (segments.length <= 0) {
throw new IllegalArgumentException("resourceLink");
}
List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null;
PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false);
if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) {
throw new IllegalArgumentException(permission.getResourceLink());
}
partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName);
if (partitionKeyAndResourceTokenPairs == null) {
partitionKeyAndResourceTokenPairs = new ArrayList<>();
this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs);
}
PartitionKey partitionKey = permission.getResourcePartitionKey();
partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair(
partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty,
permission.getToken()));
logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]",
pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken());
}
if(this.resourceTokensMap.isEmpty()) {
throw new IllegalArgumentException("permissionFeed");
}
String firstToken = permissionFeed.get(0).getToken();
if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) {
this.firstResourceTokenFromPermissionFeed = firstToken;
}
}
}
RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
activeClientsCnt.incrementAndGet();
this.clientId = clientIdGenerator.incrementAndGet();
this.diagnosticsClientConfig = new DiagnosticsClientConfig();
this.diagnosticsClientConfig.withClientId(this.clientId);
this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt);
this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled);
this.diagnosticsClientConfig.withConsistency(consistencyLevel);
this.throughputControlEnabled = new AtomicBoolean(false);
logger.info(
"Initializing DocumentClient [{}] with"
+ " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]",
this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol());
try {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
this.configs = configs;
this.masterKeyOrResourceToken = masterKeyOrResourceToken;
this.serviceEndpoint = serviceEndpoint;
this.credential = credential;
this.tokenCredential = tokenCredential;
this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled;
this.authorizationTokenType = AuthorizationTokenType.Invalid;
if (this.credential != null) {
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.authorizationTokenProvider = null;
hasAuthKeyResourceToken = true;
this.authorizationTokenType = AuthorizationTokenType.ResourceToken;
} else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken);
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else {
hasAuthKeyResourceToken = false;
this.authorizationTokenProvider = null;
if (tokenCredential != null) {
this.tokenCredentialScopes = new String[] {
serviceEndpoint.getScheme() + ":
};
this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential
.getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes)));
this.authorizationTokenType = AuthorizationTokenType.AadToken;
}
}
if (connectionPolicy != null) {
this.connectionPolicy = connectionPolicy;
} else {
this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig());
}
this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode());
this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled());
this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled());
this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions());
this.diagnosticsClientConfig.withMachineId(tempMachineId);
boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled);
this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing);
this.consistencyLevel = consistencyLevel;
this.userAgentContainer = new UserAgentContainer();
String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix();
if (userAgentSuffix != null && userAgentSuffix.length() > 0) {
userAgentContainer.setSuffix(userAgentSuffix);
}
this.httpClientInterceptor = null;
this.reactorHttpClient = httpClient();
this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs);
this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy);
this.resetSessionTokenRetryPolicy = retryPolicy;
CpuMemoryMonitor.register(this);
this.queryPlanCache = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE));
this.apiType = apiType;
} catch (RuntimeException e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
}
@Override
public DiagnosticsClientConfig getConfig() {
return diagnosticsClientConfig;
}
@Override
public CosmosDiagnostics createDiagnostics() {
return BridgeInternal.createCosmosDiagnostics(this, this.globalEndpointManager);
}
private void initializeGatewayConfigurationReader() {
this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager);
DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount();
if (databaseAccount == null) {
logger.error("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
throw new RuntimeException("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
}
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount);
}
private void updateGatewayProxy() {
((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader);
((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache);
((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache);
((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations);
}
public void serialize(CosmosClientMetadataCachesSnapshot state) {
RxCollectionCache.serialize(state, this.collectionCache);
}
private void initializeDirectConnectivity() {
this.addressResolver = new GlobalAddressResolver(this,
this.reactorHttpClient,
this.globalEndpointManager,
this.configs.getProtocol(),
this,
this.collectionCache,
this.partitionKeyRangeCache,
userAgentContainer,
null,
this.connectionPolicy,
this.apiType);
this.storeClientFactory = new StoreClientFactory(
this.addressResolver,
this.diagnosticsClientConfig,
this.configs,
this.connectionPolicy,
this.userAgentContainer,
this.connectionSharingAcrossClientsEnabled,
this.clientTelemetry
);
this.createStoreModel(true);
}
DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() {
return new DatabaseAccountManagerInternal() {
@Override
public URI getServiceEndpoint() {
return RxDocumentClientImpl.this.getServiceEndpoint();
}
@Override
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
logger.info("Getting database account endpoint from {}", endpoint);
return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return RxDocumentClientImpl.this.getConnectionPolicy();
}
};
}
RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer,
ConsistencyLevel consistencyLevel,
QueryCompatibilityMode queryCompatibilityMode,
UserAgentContainer userAgentContainer,
GlobalEndpointManager globalEndpointManager,
HttpClient httpClient,
ApiType apiType) {
return new RxGatewayStoreModel(
this,
sessionContainer,
consistencyLevel,
queryCompatibilityMode,
userAgentContainer,
globalEndpointManager,
httpClient,
apiType);
}
private HttpClient httpClient() {
HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs)
.withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout())
.withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize())
.withProxy(this.connectionPolicy.getProxy())
.withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout());
if (connectionSharingAcrossClientsEnabled) {
return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig);
} else {
diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig);
return HttpClient.createFixed(httpClientConfig);
}
}
private void createStoreModel(boolean subscribeRntbdStatus) {
StoreClient storeClient = this.storeClientFactory.createStoreClient(this,
this.addressResolver,
this.sessionContainer,
this.gatewayConfigurationReader,
this,
this.useMultipleWriteLocations
);
this.storeModel = new ServerStoreModel(storeClient);
}
@Override
public URI getServiceEndpoint() {
return this.serviceEndpoint;
}
@Override
public URI getWriteEndpoint() {
return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null);
}
@Override
public URI getReadEndpoint() {
return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return this.connectionPolicy;
}
@Override
public boolean isContentResponseOnWriteEnabled() {
return contentResponseOnWriteEnabled;
}
@Override
public ConsistencyLevel getConsistencyLevel() {
return consistencyLevel;
}
@Override
public ClientTelemetry getClientTelemetry() {
return this.clientTelemetry;
}
@Override
public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (database == null) {
throw new IllegalArgumentException("Database");
}
logger.debug("Creating a Database. id: [{}]", database.getId());
validateResource(database);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Reading a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT);
}
private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) {
switch (resourceTypeEnum) {
case Database:
return Paths.DATABASES_ROOT;
case DocumentCollection:
return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT);
case Document:
return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT);
case Offer:
return Paths.OFFERS_ROOT;
case User:
return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT);
case ClientEncryptionKey:
return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
case Permission:
return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT);
case Attachment:
return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT);
case StoredProcedure:
return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
case Trigger:
return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT);
case UserDefinedFunction:
return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
case Conflict:
return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT);
default:
throw new IllegalArgumentException("resource type not supported");
}
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) {
if (options == null) {
return null;
}
return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options);
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) {
if (options == null) {
return null;
}
return options.getOperationContextAndListenerTuple();
}
private <T extends Resource> Flux<FeedResponse<T>> createQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum) {
String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum);
UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getCorrelationActivityId(options);
UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ?
correlationActivityIdOfRequestOptions : Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this,
getOperationContextAndListenerTuple(options));
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> createQueryInternal(
resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId),
invalidPartitionExceptionRetryPolicy);
}
private <T extends Resource> Flux<FeedResponse<T>> createQueryInternal(
String resourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
IDocumentQueryClient queryClient,
UUID activityId) {
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory
.createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery,
options, resourceLink, false, activityId,
Configs.isQueryPlanCachingEnabled(), queryPlanCache);
AtomicBoolean isFirstResponse = new AtomicBoolean(true);
return executionContext.flatMap(iDocumentQueryExecutionContext -> {
QueryInfo queryInfo = null;
if (iDocumentQueryExecutionContext instanceof PipelinedDocumentQueryExecutionContext) {
queryInfo = ((PipelinedDocumentQueryExecutionContext<T>) iDocumentQueryExecutionContext).getQueryInfo();
}
QueryInfo finalQueryInfo = queryInfo;
return iDocumentQueryExecutionContext.executeAsync()
.map(tFeedResponse -> {
if (finalQueryInfo != null) {
if (finalQueryInfo.hasSelectValue()) {
ModelBridgeInternal
.addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo);
}
if (isFirstResponse.compareAndSet(true, false)) {
ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse,
finalQueryInfo.getQueryPlanDiagnosticsContext());
}
}
return tFeedResponse;
});
});
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) {
return queryDatabases(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database);
}
@Override
public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink,
DocumentCollection collection, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink,
DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink,
collection.getId());
validateResource(collection);
String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
});
} catch (Exception e) {
logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Replacing a Collection. id: [{}]", collection.getId());
validateResource(collection);
String path = Utils.joinPath(collection.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
if (resourceResponse.getResource() != null) {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
}
});
} catch (Exception e) {
logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.DELETE)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated));
}
private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated ->
this.getStoreProxy(requestPopulated).processMessage(requestPopulated)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
));
}
@Override
public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class,
Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection);
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection);
}
private static String serializeProcedureParams(List<Object> objectArray) {
String[] stringArray = new String[objectArray.size()];
for (int i = 0; i < objectArray.size(); ++i) {
Object object = objectArray.get(i);
if (object instanceof JsonSerializable) {
stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object);
} else {
try {
stringArray[i] = mapper.writeValueAsString(object);
} catch (IOException e) {
throw new IllegalArgumentException("Can't serialize the object into the json string", e);
}
}
}
return String.format("[%s]", StringUtils.join(stringArray, ","));
}
private static void validateResource(Resource resource) {
if (!StringUtils.isEmpty(resource.getId())) {
if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 ||
resource.getId().indexOf('?') != -1 || resource.getId().indexOf('
throw new IllegalArgumentException("Id contains illegal chars.");
}
if (resource.getId().endsWith(" ")) {
throw new IllegalArgumentException("Id ends with a space.");
}
}
}
private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) {
Map<String, String> headers = new HashMap<>();
if (this.useMultipleWriteLocations) {
headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString());
}
if (consistencyLevel != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString());
}
if (options == null) {
if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
return headers;
}
Map<String, String> customOptions = options.getHeaders();
if (customOptions != null) {
headers.putAll(customOptions);
}
boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled;
if (options.isContentResponseOnWriteEnabled() != null) {
contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled();
}
if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
if (options.getIfMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag());
}
if(options.getIfNoneMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag());
}
if (options.getConsistencyLevel() != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString());
}
if (options.getIndexingDirective() != null) {
headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString());
}
if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) {
String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude);
}
if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) {
String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude);
}
if (!Strings.isNullOrEmpty(options.getSessionToken())) {
headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken());
}
if (options.getResourceTokenExpirySeconds() != null) {
headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY,
String.valueOf(options.getResourceTokenExpirySeconds()));
}
if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString());
} else if (options.getOfferType() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType());
}
if (options.getOfferThroughput() == null) {
if (options.getThroughputProperties() != null) {
Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties());
final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings();
OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null;
if (offerAutoscaleSettings != null) {
autoscaleAutoUpgradeProperties
= offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties();
}
if (offer.hasOfferThroughput() &&
(offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 ||
autoscaleAutoUpgradeProperties != null &&
autoscaleAutoUpgradeProperties
.getAutoscaleThroughputProperties()
.getIncrementPercent() >= 0)) {
throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with "
+ "fixed offer");
}
if (offer.hasOfferThroughput()) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput()));
} else if (offer.getOfferAutoScaleSettings() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS,
ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings()));
}
}
}
if (options.isQuotaInfoEnabled()) {
headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true));
}
if (options.isScriptLoggingEnabled()) {
headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true));
}
if (options.getDedicatedGatewayRequestOptions() != null &&
options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) {
headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS,
String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions())));
}
return headers;
}
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return this.resetSessionTokenRetryPolicy;
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Document document,
RequestOptions options) {
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs
.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object document,
RequestOptions options,
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) {
return collectionObs.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private void addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object objectDoc, RequestOptions options,
DocumentCollection collection) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
PartitionKeyInternal partitionKeyInternal = null;
if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else if (options != null && options.getPartitionKey() != null) {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey());
} else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) {
partitionKeyInternal = PartitionKeyInternal.getEmpty();
} else if (contentAsByteBuffer != null || objectDoc != null) {
InternalObjectNode internalObjectNode;
if (objectDoc instanceof InternalObjectNode) {
internalObjectNode = (InternalObjectNode) objectDoc;
} else if (objectDoc instanceof ObjectNode) {
internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc);
} else if (contentAsByteBuffer != null) {
contentAsByteBuffer.rewind();
internalObjectNode = new InternalObjectNode(contentAsByteBuffer);
} else {
throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null");
}
Instant serializationStartTime = Instant.now();
partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTime,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION
);
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
} else {
throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation.");
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
}
public static PartitionKeyInternal extractPartitionKeyValueFromDocument(
InternalObjectNode document,
PartitionKeyDefinition partitionKeyDefinition) {
if (partitionKeyDefinition != null) {
switch (partitionKeyDefinition.getKind()) {
case HASH:
String path = partitionKeyDefinition.getPaths().iterator().next();
List<String> parts = PathParser.getPathParts(path);
if (parts.size() >= 1) {
Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts);
if (value == null || value.getClass() == ObjectNode.class) {
value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
}
if (value instanceof PartitionKeyInternal) {
return (PartitionKeyInternal) value;
} else {
return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false);
}
}
break;
case MULTI_HASH:
Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()];
for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){
String partitionPath = partitionKeyDefinition.getPaths().get(pathIter);
List<String> partitionPathParts = PathParser.getPathParts(partitionPath);
partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts);
}
return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false);
default:
throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind());
}
}
return null;
}
private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
Object document,
RequestOptions options,
boolean disableAutomaticIdGeneration,
OperationType operationType) {
if (StringUtils.isEmpty(documentCollectionLink)) {
throw new IllegalArgumentException("documentCollectionLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Document, path, requestHeaders, options, content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return addPartitionKeyInformation(request, content, document, options, collectionObs);
}
private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink");
checkNotNull(serverBatchRequest, "expected non null serverBatchRequest");
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody()));
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Batch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> {
addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v);
return request;
});
}
private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request,
ServerBatchRequest serverBatchRequest,
DocumentCollection collection) {
if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) {
PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue();
PartitionKeyInternal partitionKeyInternal;
if (partitionKey.equals(PartitionKey.NONE)) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey);
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
} else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) {
request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId()));
} else {
throw new UnsupportedOperationException("Unknown Server request.");
}
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString());
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch()));
request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError()));
request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size());
return request;
}
private Mono<RxDocumentServiceRequest> populateHeaders(RxDocumentServiceRequest request, RequestVerb httpMethod) {
request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123());
if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null
|| this.cosmosAuthorizationTokenResolver != null || this.credential != null) {
String resourceName = request.getResourceAddress();
String authorization = this.getUserAuthorizationToken(
resourceName, request.getResourceType(), httpMethod, request.getHeaders(),
AuthorizationTokenType.PrimaryMasterKey, request.properties);
try {
authorization = URLEncoder.encode(authorization, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Failed to encode authtoken.", e);
}
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
}
if (this.apiType != null) {
request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString());
}
if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod))
&& !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
}
if (RequestVerb.PATCH.equals(httpMethod) &&
!request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH);
}
if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) {
request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
}
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
if (this.requiresFeedRangeFiltering(request)) {
return request.getFeedRange()
.populateFeedRangeFilteringHeaders(
this.getPartitionKeyRangeCache(),
request,
this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request))
.flatMap(this::populateAuthorizationHeader);
}
return this.populateAuthorizationHeader(request);
}
private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) {
if (request.getResourceType() != ResourceType.Document &&
request.getResourceType() != ResourceType.Conflict) {
return false;
}
switch (request.getOperationType()) {
case ReadFeed:
case Query:
case SqlQuery:
return request.getFeedRange() != null;
default:
return false;
}
}
@Override
public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) {
if (request == null) {
throw new IllegalArgumentException("request");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return request;
});
} else {
return Mono.just(request);
}
}
@Override
public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) {
if (httpHeaders == null) {
throw new IllegalArgumentException("httpHeaders");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return httpHeaders;
});
}
return Mono.just(httpHeaders);
}
@Override
public AuthorizationTokenType getAuthorizationTokenType() {
return this.authorizationTokenType;
}
@Override
public String getUserAuthorizationToken(String resourceName,
ResourceType resourceType,
RequestVerb requestVerb,
Map<String, String> headers,
AuthorizationTokenType tokenType,
Map<String, Object> properties) {
if (this.cosmosAuthorizationTokenResolver != null) {
return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(),
properties != null ? Collections.unmodifiableMap(properties) : null);
} else if (credential != null) {
return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName,
resourceType, headers);
} else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) {
return masterKeyOrResourceToken;
} else {
assert resourceTokensMap != null;
if(resourceType.equals(ResourceType.DatabaseAccount)) {
return this.firstResourceTokenFromPermissionFeed;
}
return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers);
}
}
private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) {
CosmosResourceType cosmosResourceType =
ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString());
if (cosmosResourceType == null) {
return CosmosResourceType.SYSTEM;
}
return cosmosResourceType;
}
void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) {
this.sessionContainer.setSessionToken(request, response.getResponseHeaders());
}
private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
Map<String, String> headers = requestPopulated.getHeaders();
assert (headers != null);
headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true");
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
);
});
}
private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.PUT)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PATCH);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(request).processMessage(request);
}
@Override
public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) {
try {
logger.debug("Creating a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Create);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance);
}
private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Upsert);
Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = Utils.getCollectionName(documentLink);
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Document typedDocument = documentFromObject(document, mapper);
return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = document.getSelfLink();
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (document == null) {
throw new IllegalArgumentException("document");
}
return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a database due to [{}]", e.getMessage());
return Mono.error(e);
}
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink,
Document document,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
if (document == null) {
throw new IllegalArgumentException("document");
}
logger.debug("Replacing a Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = serializeJsonToByteBuffer(document);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs);
return requestObs.flatMap(req -> replace(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> patchDocument(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink");
checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations");
logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options));
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Patch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(
request,
null,
null,
options,
collectionObs);
return requestObs.flatMap(req -> patch(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy);
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Deleting a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs);
return requestObs.flatMap(req -> this
.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> this
.deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting documents due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Reading a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> {
return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Document>> readDocuments(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return queryDocuments(collectionLink, "SELECT * FROM r", options);
}
@Override
public <T> Mono<FeedResponse<T>> readMany(
List<CosmosItemIdentity> itemIdentityList,
String collectionLink,
CosmosQueryRequestOptions options,
Class<T> klass) {
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink, null
);
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request);
return collectionObs
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache
.tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null);
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap =
new HashMap<>();
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
itemIdentityList
.forEach(itemIdentity -> {
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(
itemIdentity.getPartitionKey()),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
if (partitionRangeItemKeyMap.get(range) == null) {
List<CosmosItemIdentity> list = new ArrayList<>();
list.add(itemIdentity);
partitionRangeItemKeyMap.put(range, list);
} else {
List<CosmosItemIdentity> pairs =
partitionRangeItemKeyMap.get(range);
pairs.add(itemIdentity);
partitionRangeItemKeyMap.put(range, pairs);
}
});
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap;
rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap,
collection.getPartitionKey());
return createReadManyQuery(
resourceLink,
new SqlQuerySpec(DUMMY_SQL_QUERY),
options,
Document.class,
ResourceType.Document,
collection,
Collections.unmodifiableMap(rangeQueryMap))
.collectList()
.map(feedList -> {
List<T> finalList = new ArrayList<>();
HashMap<String, String> headers = new HashMap<>();
ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>();
double requestCharge = 0;
for (FeedResponse<Document> page : feedList) {
ConcurrentMap<String, QueryMetrics> pageQueryMetrics =
ModelBridgeInternal.queryMetrics(page);
if (pageQueryMetrics != null) {
pageQueryMetrics.forEach(
aggregatedQueryMetrics::putIfAbsent);
}
requestCharge += page.getRequestCharge();
finalList.addAll(page.getResults().stream().map(document ->
ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList()));
}
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double
.toString(requestCharge));
FeedResponse<T> frp = BridgeInternal
.createFeedResponse(finalList, headers);
return frp;
});
});
}
);
}
private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap(
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap,
PartitionKeyDefinition partitionKeyDefinition) {
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>();
String partitionKeySelector = createPkSelector(partitionKeyDefinition);
for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) {
SqlQuerySpec sqlQuerySpec;
if (partitionKeySelector.equals("[\"id\"]")) {
sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector);
} else {
sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector);
}
rangeQueryMap.put(entry.getKey(), sqlQuerySpec);
}
return rangeQueryMap;
}
private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(
List<CosmosItemIdentity> idPartitionKeyPairList,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( ");
for (int i = 0; i < idPartitionKeyPairList.size(); i++) {
CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i);
String idValue = itemIdentity.getId();
String idParamName = "@param" + i;
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
if (!Objects.equals(idValue, pkValue)) {
continue;
}
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append(idParamName);
if (i < idPartitionKeyPairList.size() - 1) {
queryStringBuilder.append(", ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE ( ");
for (int i = 0; i < itemIdentities.size(); i++) {
CosmosItemIdentity itemIdentity = itemIdentities.get(i);
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
String pkParamName = "@param" + (2 * i);
parameters.add(new SqlParameter(pkParamName, pkValue));
String idValue = itemIdentity.getId();
String idParamName = "@param" + (2 * i + 1);
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append("(");
queryStringBuilder.append("c.id = ");
queryStringBuilder.append(idParamName);
queryStringBuilder.append(" AND ");
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
queryStringBuilder.append(" )");
if (i < itemIdentities.size() - 1) {
queryStringBuilder.append(" OR ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) {
return partitionKeyDefinition.getPaths()
.stream()
.map(pathPart -> StringUtils.substring(pathPart, 1))
.map(pathPart -> StringUtils.replace(pathPart, "\"", "\\"))
.map(part -> "[\"" + part + "\"]")
.collect(Collectors.joining());
}
private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
DocumentCollection collection,
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) {
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(),
sqlQuery,
rangeQueryMap,
options,
collection.getResourceId(),
parentResourceLink,
activityId,
klass,
resourceTypeEnum);
return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync);
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, String query, CosmosQueryRequestOptions options) {
return queryDocuments(collectionLink, new SqlQuerySpec(query), options);
}
private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return new IDocumentQueryClient () {
@Override
public RxCollectionCache getCollectionCache() {
return RxDocumentClientImpl.this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return RxDocumentClientImpl.this.partitionKeyRangeCache;
}
@Override
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy;
}
@Override
public ConsistencyLevel getDefaultConsistencyLevelAsync() {
return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel();
}
@Override
public ConsistencyLevel getDesiredConsistencyLevelAsync() {
return RxDocumentClientImpl.this.consistencyLevel;
}
@Override
public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) {
if (operationContextAndListenerTuple == null) {
return RxDocumentClientImpl.this.query(request).single();
} else {
final OperationListener listener =
operationContextAndListenerTuple.getOperationListener();
final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext();
request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId());
listener.requestListener(operationContext, request);
return RxDocumentClientImpl.this.query(request).single().doOnNext(
response -> listener.responseListener(operationContext, response)
).doOnError(
ex -> listener.exceptionListener(operationContext, ex)
);
}
}
@Override
public QueryCompatibilityMode getQueryCompatibilityMode() {
return QueryCompatibilityMode.Default;
}
@Override
public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) {
return null;
}
};
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
SqlQuerySpecLogger.getInstance().logQuery(querySpec);
return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document);
}
@Override
public Flux<FeedResponse<Document>> queryDocumentChangeFeed(
final DocumentCollection collection,
final CosmosChangeFeedRequestOptions changeFeedOptions) {
checkNotNull(collection, "Argument 'collection' must not be null.");
ChangeFeedQueryImpl<Document> changeFeedQueryImpl = new ChangeFeedQueryImpl<>(
this,
ResourceType.Document,
Document.class,
collection.getAltLink(),
collection.getResourceId(),
changeFeedOptions);
return changeFeedQueryImpl.executeAsync();
}
@Override
public Flux<FeedResponse<Document>> readAllDocuments(
String collectionLink,
PartitionKey partitionKey,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (partitionKey == null) {
throw new IllegalArgumentException("partitionKey");
}
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null
);
Flux<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request).flux();
return collectionObs.flatMap(documentCollectionResourceResponse -> {
DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
String pkSelector = createPkSelector(pkDefinition);
SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector);
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
final CosmosQueryRequestOptions effectiveOptions =
ModelBridgeInternal.createQueryRequestOptions(options);
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> {
Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache
.tryLookupAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null).flux();
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(partitionKey),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
return createQueryInternal(
resourceLink,
querySpec,
ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()),
Document.class,
ResourceType.Document,
queryClient,
activityId);
});
},
invalidPartitionExceptionRetryPolicy);
});
}
@Override
public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() {
return queryPlanCache;
}
@Override
public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class,
Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT));
}
private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
validateResource(storedProcedure);
String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType,
ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
return request;
}
private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (udf == null) {
throw new IllegalArgumentException("udf");
}
validateResource(udf);
String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Create);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId());
RxDocumentClientImpl.validateResource(storedProcedure);
String path = Utils.joinPath(storedProcedure.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class,
Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
List<Object> procedureParams) {
return this.executeStoredProcedure(storedProcedureLink, null, procedureParams);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy);
}
@Override
public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy);
}
private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) {
try {
logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript);
requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ExecuteJavaScript,
ResourceType.StoredProcedure, path,
procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "",
requestHeaders, options);
if (retryPolicy != null) {
retryPolicy.onBeforeSendRequest(request);
}
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options))
.map(response -> {
this.captureSessionToken(request, response);
return toStoredProcedureResponse(response);
}));
} catch (Exception e) {
logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
DocumentClientRetryPolicy requestRetryPolicy,
boolean disableAutomaticIdGeneration) {
try {
logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size());
Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true));
} catch (Exception ex) {
logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex);
return Mono.error(ex);
}
}
@Override
public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path,
trigger, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId());
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(trigger.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Trigger, Trigger.class,
Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryTriggers(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger);
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (udf == null) {
throw new IllegalArgumentException("udf");
}
logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId());
validateResource(udf);
String path = Utils.joinPath(udf.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class,
Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
String query, CosmosQueryRequestOptions options) {
return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction);
}
@Override
public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Conflict, Conflict.class,
Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryConflicts(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict);
}
@Override
public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (user == null) {
throw new IllegalArgumentException("user");
}
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.User, path, user, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (user == null) {
throw new IllegalArgumentException("user");
}
logger.debug("Replacing a User. user id [{}]", user.getId());
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(user.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.User, path, user, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Deleting a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Reading a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.User, User.class,
Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) {
return queryUsers(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User);
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(clientEncryptionKeyLink)) {
throw new IllegalArgumentException("clientEncryptionKeyLink");
}
logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink);
String path = Utils.joinPath(clientEncryptionKeyLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink,
ClientEncryptionKey clientEncryptionKey, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId());
RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey,
String nameBasedLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey,
nameBasedLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId());
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(nameBasedLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey,
OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders,
options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class,
Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey);
}
@Override
public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy());
}
private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
if (permission == null) {
throw new IllegalArgumentException("permission");
}
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Permission, path, permission, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (permission == null) {
throw new IllegalArgumentException("permission");
}
logger.debug("Replacing a Permission. permission id [{}]", permission.getId());
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(permission.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Reading a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
return readFeed(options, ResourceType.Permission, Permission.class,
Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query,
CosmosQueryRequestOptions options) {
return queryPermissions(userLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission);
}
@Override
public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
if (offer == null) {
throw new IllegalArgumentException("offer");
}
logger.debug("Replacing an Offer. offer id [{}]", offer.getId());
RxDocumentClientImpl.validateResource(offer);
String path = Utils.joinPath(offer.getSelfLink(), null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace,
ResourceType.Offer, path, offer, null, null);
return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Offer>> readOffer(String offerLink) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(offerLink)) {
throw new IllegalArgumentException("offerLink");
}
logger.debug("Reading an Offer. offerLink [{}]", offerLink);
String path = Utils.joinPath(offerLink, null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Offer, Offer.class,
Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null));
}
private <T extends Resource> Flux<FeedResponse<T>> readFeed(CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options);
int maxPageSize = maxItemCount != null ? maxItemCount : -1;
final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options;
DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> {
Map<String, String> requestHeaders = new HashMap<>();
if (continuationToken != null) {
requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken);
}
requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize));
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions);
retryPolicy.onBeforeSendRequest(request);
return request;
};
Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper
.inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)),
retryPolicy);
return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, maxPageSize);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) {
return queryOffers(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer);
}
@Override
public Mono<DatabaseAccount> getDatabaseAccount() {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy),
documentClientRetryPolicy);
}
@Override
public DatabaseAccount getLatestDatabaseAccount() {
return this.globalEndpointManager.getLatestDatabaseAccount();
}
private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Getting Database Account");
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read,
ResourceType.DatabaseAccount, "",
(HashMap<String, String>) null,
null);
return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount);
} catch (Exception e) {
logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Object getSession() {
return this.sessionContainer;
}
public void setSession(Object sessionContainer) {
this.sessionContainer = (SessionContainer) sessionContainer;
}
@Override
public RxClientCollectionCache getCollectionCache() {
return this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return partitionKeyRangeCache;
}
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
return Flux.defer(() -> {
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null);
return this.populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
requestPopulated.setEndpointOverride(endpoint);
return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> {
String message = String.format("Failed to retrieve database account information. %s",
e.getCause() != null
? e.getCause().toString()
: e.toString());
logger.warn(message);
}).map(rsp -> rsp.getResource(DatabaseAccount.class))
.doOnNext(databaseAccount ->
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled()
&& BridgeInternal.isEnableMultipleWriteLocations(databaseAccount));
});
});
}
/**
* Certain requests must be routed through gateway even when the client connectivity mode is direct.
*
* @param request
* @return RxStoreModel
*/
private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) {
if (request.UseGatewayMode) {
return this.gatewayProxy;
}
ResourceType resourceType = request.getResourceType();
OperationType operationType = request.getOperationType();
if (resourceType == ResourceType.Offer ||
resourceType == ResourceType.ClientEncryptionKey ||
resourceType.isScript() && operationType != OperationType.ExecuteJavaScript ||
resourceType == ResourceType.PartitionKeyRange ||
resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) {
return this.gatewayProxy;
}
if (operationType == OperationType.Create
|| operationType == OperationType.Upsert) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection ||
resourceType == ResourceType.Permission) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Delete) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Replace) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Read) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else {
if ((operationType == OperationType.Query ||
operationType == OperationType.SqlQuery ||
operationType == OperationType.ReadFeed) &&
Utils.isCollectionChild(request.getResourceType())) {
if (request.getPartitionKeyRangeIdentity() == null &&
request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) {
return this.gatewayProxy;
}
}
return this.storeModel;
}
}
@Override
public void close() {
logger.info("Attempting to close client {}", this.clientId);
if (!closed.getAndSet(true)) {
activeClientsCnt.decrementAndGet();
logger.info("Shutting down ...");
logger.info("Closing Global Endpoint Manager ...");
LifeCycleUtils.closeQuietly(this.globalEndpointManager);
logger.info("Closing StoreClientFactory ...");
LifeCycleUtils.closeQuietly(this.storeClientFactory);
logger.info("Shutting down reactorHttpClient ...");
LifeCycleUtils.closeQuietly(this.reactorHttpClient);
logger.info("Shutting down CpuMonitor ...");
CpuMemoryMonitor.unregister(this);
if (this.throughputControlEnabled.get()) {
logger.info("Closing ThroughputControlStore ...");
this.throughputControlStore.close();
}
logger.info("Shutting down completed.");
} else {
logger.warn("Already shutdown!");
}
}
@Override
public ItemDeserializer getItemDeserializer() {
return this.itemDeserializer;
}
@Override
public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group can not be null");
if (this.throughputControlEnabled.compareAndSet(false, true)) {
this.throughputControlStore =
new ThroughputControlStore(
this.collectionCache,
this.connectionPolicy.getConnectionMode(),
this.partitionKeyRangeCache);
this.storeModel.enableThroughputControl(throughputControlStore);
}
this.throughputControlStore.enableThroughputControlGroup(group);
}
private static SqlQuerySpec createLogicalPartitionScanQuerySpec(
PartitionKey partitionKey,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE");
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey);
String pkParamName = "@pkValue";
parameters.add(new SqlParameter(pkParamName, pkValue));
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
@Override
public Mono<List<FeedRange>> getFeedRanges(String collectionLink) {
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
collectionLink,
new HashMap<>());
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null);
invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request);
return ObservableHelper.inlineIfPossibleAsObs(
() -> getFeedRangesInternal(request, collectionLink),
invalidPartitionExceptionRetryPolicy);
}
private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) {
logger.debug("getFeedRange collectionLink=[{}]", collectionLink);
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null,
request);
return collectionObs.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache
.tryGetOverlappingRangesAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null);
return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request));
});
}
private static List<FeedRange> toFeedRanges(
Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) {
final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v;
if (partitionKeyRangeList == null) {
request.forceNameCacheRefresh = true;
throw new InvalidPartitionException();
}
List<FeedRange> feedRanges = new ArrayList<>();
partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange)));
return feedRanges;
}
private static FeedRange toFeedRange(PartitionKeyRange pkRange) {
return new FeedRangeEpkImpl(pkRange.toRange());
}
} |
I see we have clientId which is getting calculated via clientIdGenerator , can we use that in here instead of UUID ? We already have unique process Id and VmID now , so this will align clientId in diagnostics and telemetry | public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) {
try {
this.httpClientInterceptor = httpClientInterceptor;
if (httpClientInterceptor != null) {
this.reactorHttpClient = httpClientInterceptor.apply(httpClient());
}
this.gatewayProxy = createRxGatewayProxy(this.sessionContainer,
this.consistencyLevel,
this.queryCompatibilityMode,
this.userAgentContainer,
this.globalEndpointManager,
this.reactorHttpClient,
this.apiType);
this.globalEndpointManager.init();
this.initializeGatewayConfigurationReader();
if (metadataCachesSnapshot != null) {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy,
metadataCachesSnapshot.getCollectionInfoByNameCache(),
metadataCachesSnapshot.getCollectionInfoByIdCache()
);
} else {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy);
}
this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy);
this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this,
collectionCache);
updateGatewayProxy();
clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(),
ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(),
connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(),
null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions());
clientTelemetry.init();
if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) {
this.storeModel = this.gatewayProxy;
} else {
this.initializeDirectConnectivity();
}
this.retryPolicy.setRxCollectionCache(this.collectionCache);
} catch (Exception e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
} | clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(), | public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) {
try {
this.httpClientInterceptor = httpClientInterceptor;
if (httpClientInterceptor != null) {
this.reactorHttpClient = httpClientInterceptor.apply(httpClient());
}
this.gatewayProxy = createRxGatewayProxy(this.sessionContainer,
this.consistencyLevel,
this.queryCompatibilityMode,
this.userAgentContainer,
this.globalEndpointManager,
this.reactorHttpClient,
this.apiType);
this.globalEndpointManager.init();
this.initializeGatewayConfigurationReader();
if (metadataCachesSnapshot != null) {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy,
metadataCachesSnapshot.getCollectionInfoByNameCache(),
metadataCachesSnapshot.getCollectionInfoByIdCache()
);
} else {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy);
}
this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy);
this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this,
collectionCache);
updateGatewayProxy();
clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(),
ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(),
connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(),
null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions());
clientTelemetry.init();
if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) {
this.storeModel = this.gatewayProxy;
} else {
this.initializeDirectConnectivity();
}
this.retryPolicy.setRxCollectionCache(this.collectionCache);
} catch (Exception e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
} | class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener,
DiagnosticsClientContext {
private static final String tempMachineId = "uuid:" + UUID.randomUUID();
private static final AtomicInteger activeClientsCnt = new AtomicInteger(0);
private static final AtomicInteger clientIdGenerator = new AtomicInteger(0);
private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>(
PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey,
PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false);
private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " +
"ParallelDocumentQueryExecutioncontext, but not used";
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper();
private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer();
private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class);
private final String masterKeyOrResourceToken;
private final URI serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel consistencyLevel;
private final BaseAuthorizationTokenProvider authorizationTokenProvider;
private final UserAgentContainer userAgentContainer;
private final boolean hasAuthKeyResourceToken;
private final Configs configs;
private final boolean connectionSharingAcrossClientsEnabled;
private AzureKeyCredential credential;
private final TokenCredential tokenCredential;
private String[] tokenCredentialScopes;
private SimpleTokenCache tokenCredentialCache;
private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver;
AuthorizationTokenType authorizationTokenType;
private SessionContainer sessionContainer;
private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY;
private RxClientCollectionCache collectionCache;
private RxStoreModel gatewayProxy;
private RxStoreModel storeModel;
private GlobalAddressResolver addressResolver;
private RxPartitionKeyRangeCache partitionKeyRangeCache;
private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap;
private final boolean contentResponseOnWriteEnabled;
private Map<String, PartitionedQueryExecutionInfo> queryPlanCache;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final int clientId;
private ClientTelemetry clientTelemetry;
private ApiType apiType;
private IRetryPolicyFactory resetSessionTokenRetryPolicy;
/**
* Compatibility mode: Allows to specify compatibility mode used by client when
* making query requests. Should be removed when application/sql is no longer
* supported.
*/
private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default;
private final GlobalEndpointManager globalEndpointManager;
private final RetryPolicy retryPolicy;
private HttpClient reactorHttpClient;
private Function<HttpClient, HttpClient> httpClientInterceptor;
private volatile boolean useMultipleWriteLocations;
private StoreClientFactory storeClientFactory;
private GatewayServiceConfigurationReader gatewayConfigurationReader;
private final DiagnosticsClientConfig diagnosticsClientConfig;
private final AtomicBoolean throughputControlEnabled;
private ThroughputControlStore throughputControlStore;
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
private RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
if (permissionFeed != null && permissionFeed.size() > 0) {
this.resourceTokensMap = new HashMap<>();
for (Permission permission : permissionFeed) {
String[] segments = StringUtils.split(permission.getResourceLink(),
Constants.Properties.PATH_SEPARATOR.charAt(0));
if (segments.length <= 0) {
throw new IllegalArgumentException("resourceLink");
}
List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null;
PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false);
if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) {
throw new IllegalArgumentException(permission.getResourceLink());
}
partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName);
if (partitionKeyAndResourceTokenPairs == null) {
partitionKeyAndResourceTokenPairs = new ArrayList<>();
this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs);
}
PartitionKey partitionKey = permission.getResourcePartitionKey();
partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair(
partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty,
permission.getToken()));
logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]",
pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken());
}
if(this.resourceTokensMap.isEmpty()) {
throw new IllegalArgumentException("permissionFeed");
}
String firstToken = permissionFeed.get(0).getToken();
if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) {
this.firstResourceTokenFromPermissionFeed = firstToken;
}
}
}
RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
activeClientsCnt.incrementAndGet();
this.clientId = clientIdGenerator.incrementAndGet();
this.diagnosticsClientConfig = new DiagnosticsClientConfig();
this.diagnosticsClientConfig.withClientId(this.clientId);
this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt);
this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled);
this.diagnosticsClientConfig.withConsistency(consistencyLevel);
this.throughputControlEnabled = new AtomicBoolean(false);
logger.info(
"Initializing DocumentClient [{}] with"
+ " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]",
this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol());
try {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
this.configs = configs;
this.masterKeyOrResourceToken = masterKeyOrResourceToken;
this.serviceEndpoint = serviceEndpoint;
this.credential = credential;
this.tokenCredential = tokenCredential;
this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled;
this.authorizationTokenType = AuthorizationTokenType.Invalid;
if (this.credential != null) {
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.authorizationTokenProvider = null;
hasAuthKeyResourceToken = true;
this.authorizationTokenType = AuthorizationTokenType.ResourceToken;
} else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken);
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else {
hasAuthKeyResourceToken = false;
this.authorizationTokenProvider = null;
if (tokenCredential != null) {
this.tokenCredentialScopes = new String[] {
serviceEndpoint.getScheme() + ":
};
this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential
.getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes)));
this.authorizationTokenType = AuthorizationTokenType.AadToken;
}
}
if (connectionPolicy != null) {
this.connectionPolicy = connectionPolicy;
} else {
this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig());
}
this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode());
this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled());
this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled());
this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions());
this.diagnosticsClientConfig.withMachineId(tempMachineId);
boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled);
this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing);
this.consistencyLevel = consistencyLevel;
this.userAgentContainer = new UserAgentContainer();
String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix();
if (userAgentSuffix != null && userAgentSuffix.length() > 0) {
userAgentContainer.setSuffix(userAgentSuffix);
}
this.httpClientInterceptor = null;
this.reactorHttpClient = httpClient();
this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs);
this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy);
this.resetSessionTokenRetryPolicy = retryPolicy;
CpuMemoryMonitor.register(this);
this.queryPlanCache = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE));
this.apiType = apiType;
} catch (RuntimeException e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
}
@Override
public DiagnosticsClientConfig getConfig() {
return diagnosticsClientConfig;
}
@Override
public CosmosDiagnostics createDiagnostics() {
return BridgeInternal.createCosmosDiagnostics(this, this.globalEndpointManager);
}
private void initializeGatewayConfigurationReader() {
this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager);
DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount();
if (databaseAccount == null) {
logger.error("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
throw new RuntimeException("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
}
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount);
}
private void updateGatewayProxy() {
((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader);
((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache);
((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache);
((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations);
}
public void serialize(CosmosClientMetadataCachesSnapshot state) {
RxCollectionCache.serialize(state, this.collectionCache);
}
private void initializeDirectConnectivity() {
this.addressResolver = new GlobalAddressResolver(this,
this.reactorHttpClient,
this.globalEndpointManager,
this.configs.getProtocol(),
this,
this.collectionCache,
this.partitionKeyRangeCache,
userAgentContainer,
null,
this.connectionPolicy,
this.apiType);
this.storeClientFactory = new StoreClientFactory(
this.addressResolver,
this.diagnosticsClientConfig,
this.configs,
this.connectionPolicy,
this.userAgentContainer,
this.connectionSharingAcrossClientsEnabled,
this.clientTelemetry
);
this.createStoreModel(true);
}
DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() {
return new DatabaseAccountManagerInternal() {
@Override
public URI getServiceEndpoint() {
return RxDocumentClientImpl.this.getServiceEndpoint();
}
@Override
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
logger.info("Getting database account endpoint from {}", endpoint);
return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return RxDocumentClientImpl.this.getConnectionPolicy();
}
};
}
RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer,
ConsistencyLevel consistencyLevel,
QueryCompatibilityMode queryCompatibilityMode,
UserAgentContainer userAgentContainer,
GlobalEndpointManager globalEndpointManager,
HttpClient httpClient,
ApiType apiType) {
return new RxGatewayStoreModel(
this,
sessionContainer,
consistencyLevel,
queryCompatibilityMode,
userAgentContainer,
globalEndpointManager,
httpClient,
apiType);
}
private HttpClient httpClient() {
HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs)
.withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout())
.withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize())
.withProxy(this.connectionPolicy.getProxy())
.withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout());
if (connectionSharingAcrossClientsEnabled) {
return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig);
} else {
diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig);
return HttpClient.createFixed(httpClientConfig);
}
}
private void createStoreModel(boolean subscribeRntbdStatus) {
StoreClient storeClient = this.storeClientFactory.createStoreClient(this,
this.addressResolver,
this.sessionContainer,
this.gatewayConfigurationReader,
this,
this.useMultipleWriteLocations
);
this.storeModel = new ServerStoreModel(storeClient);
}
@Override
public URI getServiceEndpoint() {
return this.serviceEndpoint;
}
@Override
public URI getWriteEndpoint() {
return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null);
}
@Override
public URI getReadEndpoint() {
return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return this.connectionPolicy;
}
@Override
public boolean isContentResponseOnWriteEnabled() {
return contentResponseOnWriteEnabled;
}
@Override
public ConsistencyLevel getConsistencyLevel() {
return consistencyLevel;
}
@Override
public ClientTelemetry getClientTelemetry() {
return this.clientTelemetry;
}
@Override
public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (database == null) {
throw new IllegalArgumentException("Database");
}
logger.debug("Creating a Database. id: [{}]", database.getId());
validateResource(database);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Reading a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT);
}
private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) {
switch (resourceTypeEnum) {
case Database:
return Paths.DATABASES_ROOT;
case DocumentCollection:
return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT);
case Document:
return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT);
case Offer:
return Paths.OFFERS_ROOT;
case User:
return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT);
case ClientEncryptionKey:
return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
case Permission:
return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT);
case Attachment:
return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT);
case StoredProcedure:
return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
case Trigger:
return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT);
case UserDefinedFunction:
return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
case Conflict:
return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT);
default:
throw new IllegalArgumentException("resource type not supported");
}
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) {
if (options == null) {
return null;
}
return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options);
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) {
if (options == null) {
return null;
}
return options.getOperationContextAndListenerTuple();
}
private <T extends Resource> Flux<FeedResponse<T>> createQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum) {
String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum);
UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getCorrelationActivityId(options);
UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ?
correlationActivityIdOfRequestOptions : Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this,
getOperationContextAndListenerTuple(options));
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> createQueryInternal(
resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId),
invalidPartitionExceptionRetryPolicy);
}
private <T extends Resource> Flux<FeedResponse<T>> createQueryInternal(
String resourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
IDocumentQueryClient queryClient,
UUID activityId) {
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory
.createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery,
options, resourceLink, false, activityId,
Configs.isQueryPlanCachingEnabled(), queryPlanCache);
AtomicBoolean isFirstResponse = new AtomicBoolean(true);
return executionContext.flatMap(iDocumentQueryExecutionContext -> {
QueryInfo queryInfo = null;
if (iDocumentQueryExecutionContext instanceof PipelinedDocumentQueryExecutionContext) {
queryInfo = ((PipelinedDocumentQueryExecutionContext<T>) iDocumentQueryExecutionContext).getQueryInfo();
}
QueryInfo finalQueryInfo = queryInfo;
return iDocumentQueryExecutionContext.executeAsync()
.map(tFeedResponse -> {
if (finalQueryInfo != null) {
if (finalQueryInfo.hasSelectValue()) {
ModelBridgeInternal
.addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo);
}
if (isFirstResponse.compareAndSet(true, false)) {
ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse,
finalQueryInfo.getQueryPlanDiagnosticsContext());
}
}
return tFeedResponse;
});
});
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) {
return queryDatabases(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database);
}
@Override
public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink,
DocumentCollection collection, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink,
DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink,
collection.getId());
validateResource(collection);
String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
});
} catch (Exception e) {
logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Replacing a Collection. id: [{}]", collection.getId());
validateResource(collection);
String path = Utils.joinPath(collection.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
if (resourceResponse.getResource() != null) {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
}
});
} catch (Exception e) {
logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.DELETE)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated));
}
private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated ->
this.getStoreProxy(requestPopulated).processMessage(requestPopulated)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
));
}
@Override
public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class,
Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection);
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection);
}
private static String serializeProcedureParams(List<Object> objectArray) {
String[] stringArray = new String[objectArray.size()];
for (int i = 0; i < objectArray.size(); ++i) {
Object object = objectArray.get(i);
if (object instanceof JsonSerializable) {
stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object);
} else {
try {
stringArray[i] = mapper.writeValueAsString(object);
} catch (IOException e) {
throw new IllegalArgumentException("Can't serialize the object into the json string", e);
}
}
}
return String.format("[%s]", StringUtils.join(stringArray, ","));
}
private static void validateResource(Resource resource) {
if (!StringUtils.isEmpty(resource.getId())) {
if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 ||
resource.getId().indexOf('?') != -1 || resource.getId().indexOf('
throw new IllegalArgumentException("Id contains illegal chars.");
}
if (resource.getId().endsWith(" ")) {
throw new IllegalArgumentException("Id ends with a space.");
}
}
}
private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) {
Map<String, String> headers = new HashMap<>();
if (this.useMultipleWriteLocations) {
headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString());
}
if (consistencyLevel != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString());
}
if (options == null) {
if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
return headers;
}
Map<String, String> customOptions = options.getHeaders();
if (customOptions != null) {
headers.putAll(customOptions);
}
boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled;
if (options.isContentResponseOnWriteEnabled() != null) {
contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled();
}
if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
if (options.getIfMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag());
}
if(options.getIfNoneMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag());
}
if (options.getConsistencyLevel() != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString());
}
if (options.getIndexingDirective() != null) {
headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString());
}
if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) {
String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude);
}
if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) {
String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude);
}
if (!Strings.isNullOrEmpty(options.getSessionToken())) {
headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken());
}
if (options.getResourceTokenExpirySeconds() != null) {
headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY,
String.valueOf(options.getResourceTokenExpirySeconds()));
}
if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString());
} else if (options.getOfferType() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType());
}
if (options.getOfferThroughput() == null) {
if (options.getThroughputProperties() != null) {
Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties());
final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings();
OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null;
if (offerAutoscaleSettings != null) {
autoscaleAutoUpgradeProperties
= offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties();
}
if (offer.hasOfferThroughput() &&
(offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 ||
autoscaleAutoUpgradeProperties != null &&
autoscaleAutoUpgradeProperties
.getAutoscaleThroughputProperties()
.getIncrementPercent() >= 0)) {
throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with "
+ "fixed offer");
}
if (offer.hasOfferThroughput()) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput()));
} else if (offer.getOfferAutoScaleSettings() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS,
ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings()));
}
}
}
if (options.isQuotaInfoEnabled()) {
headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true));
}
if (options.isScriptLoggingEnabled()) {
headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true));
}
if (options.getDedicatedGatewayRequestOptions() != null &&
options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) {
headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS,
String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions())));
}
return headers;
}
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return this.resetSessionTokenRetryPolicy;
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Document document,
RequestOptions options) {
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs
.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object document,
RequestOptions options,
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) {
return collectionObs.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private void addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object objectDoc, RequestOptions options,
DocumentCollection collection) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
PartitionKeyInternal partitionKeyInternal = null;
if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else if (options != null && options.getPartitionKey() != null) {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey());
} else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) {
partitionKeyInternal = PartitionKeyInternal.getEmpty();
} else if (contentAsByteBuffer != null || objectDoc != null) {
InternalObjectNode internalObjectNode;
if (objectDoc instanceof InternalObjectNode) {
internalObjectNode = (InternalObjectNode) objectDoc;
} else if (objectDoc instanceof ObjectNode) {
internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc);
} else if (contentAsByteBuffer != null) {
contentAsByteBuffer.rewind();
internalObjectNode = new InternalObjectNode(contentAsByteBuffer);
} else {
throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null");
}
Instant serializationStartTime = Instant.now();
partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTime,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION
);
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
} else {
throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation.");
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
}
public static PartitionKeyInternal extractPartitionKeyValueFromDocument(
InternalObjectNode document,
PartitionKeyDefinition partitionKeyDefinition) {
if (partitionKeyDefinition != null) {
switch (partitionKeyDefinition.getKind()) {
case HASH:
String path = partitionKeyDefinition.getPaths().iterator().next();
List<String> parts = PathParser.getPathParts(path);
if (parts.size() >= 1) {
Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts);
if (value == null || value.getClass() == ObjectNode.class) {
value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
}
if (value instanceof PartitionKeyInternal) {
return (PartitionKeyInternal) value;
} else {
return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false);
}
}
break;
case MULTI_HASH:
Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()];
for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){
String partitionPath = partitionKeyDefinition.getPaths().get(pathIter);
List<String> partitionPathParts = PathParser.getPathParts(partitionPath);
partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts);
}
return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false);
default:
throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind());
}
}
return null;
}
private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
Object document,
RequestOptions options,
boolean disableAutomaticIdGeneration,
OperationType operationType) {
if (StringUtils.isEmpty(documentCollectionLink)) {
throw new IllegalArgumentException("documentCollectionLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Document, path, requestHeaders, options, content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return addPartitionKeyInformation(request, content, document, options, collectionObs);
}
private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink");
checkNotNull(serverBatchRequest, "expected non null serverBatchRequest");
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody()));
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Batch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> {
addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v);
return request;
});
}
private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request,
ServerBatchRequest serverBatchRequest,
DocumentCollection collection) {
if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) {
PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue();
PartitionKeyInternal partitionKeyInternal;
if (partitionKey.equals(PartitionKey.NONE)) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey);
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
} else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) {
request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId()));
} else {
throw new UnsupportedOperationException("Unknown Server request.");
}
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString());
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch()));
request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError()));
request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size());
return request;
}
private Mono<RxDocumentServiceRequest> populateHeaders(RxDocumentServiceRequest request, RequestVerb httpMethod) {
request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123());
if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null
|| this.cosmosAuthorizationTokenResolver != null || this.credential != null) {
String resourceName = request.getResourceAddress();
String authorization = this.getUserAuthorizationToken(
resourceName, request.getResourceType(), httpMethod, request.getHeaders(),
AuthorizationTokenType.PrimaryMasterKey, request.properties);
try {
authorization = URLEncoder.encode(authorization, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Failed to encode authtoken.", e);
}
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
}
if (this.apiType != null) {
request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString());
}
if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod))
&& !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
}
if (RequestVerb.PATCH.equals(httpMethod) &&
!request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH);
}
if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) {
request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
}
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
if (this.requiresFeedRangeFiltering(request)) {
return request.getFeedRange()
.populateFeedRangeFilteringHeaders(
this.getPartitionKeyRangeCache(),
request,
this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request))
.flatMap(this::populateAuthorizationHeader);
}
return this.populateAuthorizationHeader(request);
}
private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) {
if (request.getResourceType() != ResourceType.Document &&
request.getResourceType() != ResourceType.Conflict) {
return false;
}
switch (request.getOperationType()) {
case ReadFeed:
case Query:
case SqlQuery:
return request.getFeedRange() != null;
default:
return false;
}
}
@Override
public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) {
if (request == null) {
throw new IllegalArgumentException("request");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return request;
});
} else {
return Mono.just(request);
}
}
@Override
public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) {
if (httpHeaders == null) {
throw new IllegalArgumentException("httpHeaders");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return httpHeaders;
});
}
return Mono.just(httpHeaders);
}
@Override
public AuthorizationTokenType getAuthorizationTokenType() {
return this.authorizationTokenType;
}
@Override
public String getUserAuthorizationToken(String resourceName,
ResourceType resourceType,
RequestVerb requestVerb,
Map<String, String> headers,
AuthorizationTokenType tokenType,
Map<String, Object> properties) {
if (this.cosmosAuthorizationTokenResolver != null) {
return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(),
properties != null ? Collections.unmodifiableMap(properties) : null);
} else if (credential != null) {
return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName,
resourceType, headers);
} else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) {
return masterKeyOrResourceToken;
} else {
assert resourceTokensMap != null;
if(resourceType.equals(ResourceType.DatabaseAccount)) {
return this.firstResourceTokenFromPermissionFeed;
}
return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers);
}
}
private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) {
CosmosResourceType cosmosResourceType =
ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString());
if (cosmosResourceType == null) {
return CosmosResourceType.SYSTEM;
}
return cosmosResourceType;
}
void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) {
this.sessionContainer.setSessionToken(request, response.getResponseHeaders());
}
private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
Map<String, String> headers = requestPopulated.getHeaders();
assert (headers != null);
headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true");
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
);
});
}
private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.PUT)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PATCH);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(request).processMessage(request);
}
@Override
public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) {
try {
logger.debug("Creating a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Create);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance);
}
private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Upsert);
Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = Utils.getCollectionName(documentLink);
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Document typedDocument = documentFromObject(document, mapper);
return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = document.getSelfLink();
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (document == null) {
throw new IllegalArgumentException("document");
}
return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a database due to [{}]", e.getMessage());
return Mono.error(e);
}
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink,
Document document,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
if (document == null) {
throw new IllegalArgumentException("document");
}
logger.debug("Replacing a Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = serializeJsonToByteBuffer(document);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs);
return requestObs.flatMap(req -> replace(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> patchDocument(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink");
checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations");
logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options));
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Patch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(
request,
null,
null,
options,
collectionObs);
return requestObs.flatMap(req -> patch(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy);
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Deleting a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs);
return requestObs.flatMap(req -> this
.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> this
.deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting documents due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Reading a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> {
return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Document>> readDocuments(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return queryDocuments(collectionLink, "SELECT * FROM r", options);
}
@Override
public <T> Mono<FeedResponse<T>> readMany(
List<CosmosItemIdentity> itemIdentityList,
String collectionLink,
CosmosQueryRequestOptions options,
Class<T> klass) {
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink, null
);
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request);
return collectionObs
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache
.tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null);
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap =
new HashMap<>();
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
itemIdentityList
.forEach(itemIdentity -> {
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(
itemIdentity.getPartitionKey()),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
if (partitionRangeItemKeyMap.get(range) == null) {
List<CosmosItemIdentity> list = new ArrayList<>();
list.add(itemIdentity);
partitionRangeItemKeyMap.put(range, list);
} else {
List<CosmosItemIdentity> pairs =
partitionRangeItemKeyMap.get(range);
pairs.add(itemIdentity);
partitionRangeItemKeyMap.put(range, pairs);
}
});
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap;
rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap,
collection.getPartitionKey());
return createReadManyQuery(
resourceLink,
new SqlQuerySpec(DUMMY_SQL_QUERY),
options,
Document.class,
ResourceType.Document,
collection,
Collections.unmodifiableMap(rangeQueryMap))
.collectList()
.map(feedList -> {
List<T> finalList = new ArrayList<>();
HashMap<String, String> headers = new HashMap<>();
ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>();
double requestCharge = 0;
for (FeedResponse<Document> page : feedList) {
ConcurrentMap<String, QueryMetrics> pageQueryMetrics =
ModelBridgeInternal.queryMetrics(page);
if (pageQueryMetrics != null) {
pageQueryMetrics.forEach(
aggregatedQueryMetrics::putIfAbsent);
}
requestCharge += page.getRequestCharge();
finalList.addAll(page.getResults().stream().map(document ->
ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList()));
}
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double
.toString(requestCharge));
FeedResponse<T> frp = BridgeInternal
.createFeedResponse(finalList, headers);
return frp;
});
});
}
);
}
private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap(
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap,
PartitionKeyDefinition partitionKeyDefinition) {
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>();
String partitionKeySelector = createPkSelector(partitionKeyDefinition);
for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) {
SqlQuerySpec sqlQuerySpec;
if (partitionKeySelector.equals("[\"id\"]")) {
sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector);
} else {
sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector);
}
rangeQueryMap.put(entry.getKey(), sqlQuerySpec);
}
return rangeQueryMap;
}
private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(
List<CosmosItemIdentity> idPartitionKeyPairList,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( ");
for (int i = 0; i < idPartitionKeyPairList.size(); i++) {
CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i);
String idValue = itemIdentity.getId();
String idParamName = "@param" + i;
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
if (!Objects.equals(idValue, pkValue)) {
continue;
}
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append(idParamName);
if (i < idPartitionKeyPairList.size() - 1) {
queryStringBuilder.append(", ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE ( ");
for (int i = 0; i < itemIdentities.size(); i++) {
CosmosItemIdentity itemIdentity = itemIdentities.get(i);
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
String pkParamName = "@param" + (2 * i);
parameters.add(new SqlParameter(pkParamName, pkValue));
String idValue = itemIdentity.getId();
String idParamName = "@param" + (2 * i + 1);
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append("(");
queryStringBuilder.append("c.id = ");
queryStringBuilder.append(idParamName);
queryStringBuilder.append(" AND ");
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
queryStringBuilder.append(" )");
if (i < itemIdentities.size() - 1) {
queryStringBuilder.append(" OR ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) {
return partitionKeyDefinition.getPaths()
.stream()
.map(pathPart -> StringUtils.substring(pathPart, 1))
.map(pathPart -> StringUtils.replace(pathPart, "\"", "\\"))
.map(part -> "[\"" + part + "\"]")
.collect(Collectors.joining());
}
private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
DocumentCollection collection,
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) {
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(),
sqlQuery,
rangeQueryMap,
options,
collection.getResourceId(),
parentResourceLink,
activityId,
klass,
resourceTypeEnum);
return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync);
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, String query, CosmosQueryRequestOptions options) {
return queryDocuments(collectionLink, new SqlQuerySpec(query), options);
}
private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return new IDocumentQueryClient () {
@Override
public RxCollectionCache getCollectionCache() {
return RxDocumentClientImpl.this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return RxDocumentClientImpl.this.partitionKeyRangeCache;
}
@Override
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy;
}
@Override
public ConsistencyLevel getDefaultConsistencyLevelAsync() {
return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel();
}
@Override
public ConsistencyLevel getDesiredConsistencyLevelAsync() {
return RxDocumentClientImpl.this.consistencyLevel;
}
@Override
public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) {
if (operationContextAndListenerTuple == null) {
return RxDocumentClientImpl.this.query(request).single();
} else {
final OperationListener listener =
operationContextAndListenerTuple.getOperationListener();
final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext();
request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId());
listener.requestListener(operationContext, request);
return RxDocumentClientImpl.this.query(request).single().doOnNext(
response -> listener.responseListener(operationContext, response)
).doOnError(
ex -> listener.exceptionListener(operationContext, ex)
);
}
}
@Override
public QueryCompatibilityMode getQueryCompatibilityMode() {
return QueryCompatibilityMode.Default;
}
@Override
public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) {
return null;
}
};
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
SqlQuerySpecLogger.getInstance().logQuery(querySpec);
return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document);
}
@Override
public Flux<FeedResponse<Document>> queryDocumentChangeFeed(
final DocumentCollection collection,
final CosmosChangeFeedRequestOptions changeFeedOptions) {
checkNotNull(collection, "Argument 'collection' must not be null.");
ChangeFeedQueryImpl<Document> changeFeedQueryImpl = new ChangeFeedQueryImpl<>(
this,
ResourceType.Document,
Document.class,
collection.getAltLink(),
collection.getResourceId(),
changeFeedOptions);
return changeFeedQueryImpl.executeAsync();
}
@Override
public Flux<FeedResponse<Document>> readAllDocuments(
String collectionLink,
PartitionKey partitionKey,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (partitionKey == null) {
throw new IllegalArgumentException("partitionKey");
}
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null
);
Flux<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request).flux();
return collectionObs.flatMap(documentCollectionResourceResponse -> {
DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
String pkSelector = createPkSelector(pkDefinition);
SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector);
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
final CosmosQueryRequestOptions effectiveOptions =
ModelBridgeInternal.createQueryRequestOptions(options);
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> {
Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache
.tryLookupAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null).flux();
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(partitionKey),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
return createQueryInternal(
resourceLink,
querySpec,
ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()),
Document.class,
ResourceType.Document,
queryClient,
activityId);
});
},
invalidPartitionExceptionRetryPolicy);
});
}
@Override
public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() {
return queryPlanCache;
}
@Override
public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class,
Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT));
}
private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
validateResource(storedProcedure);
String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType,
ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
return request;
}
private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (udf == null) {
throw new IllegalArgumentException("udf");
}
validateResource(udf);
String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Create);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId());
RxDocumentClientImpl.validateResource(storedProcedure);
String path = Utils.joinPath(storedProcedure.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class,
Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
List<Object> procedureParams) {
return this.executeStoredProcedure(storedProcedureLink, null, procedureParams);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy);
}
@Override
public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy);
}
private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) {
try {
logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript);
requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ExecuteJavaScript,
ResourceType.StoredProcedure, path,
procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "",
requestHeaders, options);
if (retryPolicy != null) {
retryPolicy.onBeforeSendRequest(request);
}
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options))
.map(response -> {
this.captureSessionToken(request, response);
return toStoredProcedureResponse(response);
}));
} catch (Exception e) {
logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
DocumentClientRetryPolicy requestRetryPolicy,
boolean disableAutomaticIdGeneration) {
try {
logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size());
Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true));
} catch (Exception ex) {
logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex);
return Mono.error(ex);
}
}
@Override
public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path,
trigger, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId());
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(trigger.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Trigger, Trigger.class,
Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryTriggers(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger);
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (udf == null) {
throw new IllegalArgumentException("udf");
}
logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId());
validateResource(udf);
String path = Utils.joinPath(udf.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class,
Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
String query, CosmosQueryRequestOptions options) {
return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction);
}
@Override
public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Conflict, Conflict.class,
Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryConflicts(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict);
}
@Override
public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (user == null) {
throw new IllegalArgumentException("user");
}
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.User, path, user, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (user == null) {
throw new IllegalArgumentException("user");
}
logger.debug("Replacing a User. user id [{}]", user.getId());
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(user.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.User, path, user, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Deleting a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Reading a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.User, User.class,
Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) {
return queryUsers(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User);
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(clientEncryptionKeyLink)) {
throw new IllegalArgumentException("clientEncryptionKeyLink");
}
logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink);
String path = Utils.joinPath(clientEncryptionKeyLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink,
ClientEncryptionKey clientEncryptionKey, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId());
RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey,
String nameBasedLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey,
nameBasedLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId());
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(nameBasedLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey,
OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders,
options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class,
Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey);
}
@Override
public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy());
}
private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
if (permission == null) {
throw new IllegalArgumentException("permission");
}
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Permission, path, permission, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (permission == null) {
throw new IllegalArgumentException("permission");
}
logger.debug("Replacing a Permission. permission id [{}]", permission.getId());
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(permission.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Reading a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
return readFeed(options, ResourceType.Permission, Permission.class,
Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query,
CosmosQueryRequestOptions options) {
return queryPermissions(userLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission);
}
@Override
public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
if (offer == null) {
throw new IllegalArgumentException("offer");
}
logger.debug("Replacing an Offer. offer id [{}]", offer.getId());
RxDocumentClientImpl.validateResource(offer);
String path = Utils.joinPath(offer.getSelfLink(), null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace,
ResourceType.Offer, path, offer, null, null);
return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Offer>> readOffer(String offerLink) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(offerLink)) {
throw new IllegalArgumentException("offerLink");
}
logger.debug("Reading an Offer. offerLink [{}]", offerLink);
String path = Utils.joinPath(offerLink, null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Offer, Offer.class,
Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null));
}
private <T extends Resource> Flux<FeedResponse<T>> readFeed(CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options);
int maxPageSize = maxItemCount != null ? maxItemCount : -1;
final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options;
DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> {
Map<String, String> requestHeaders = new HashMap<>();
if (continuationToken != null) {
requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken);
}
requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize));
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions);
retryPolicy.onBeforeSendRequest(request);
return request;
};
Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper
.inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)),
retryPolicy);
return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, maxPageSize);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) {
return queryOffers(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer);
}
@Override
public Mono<DatabaseAccount> getDatabaseAccount() {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy),
documentClientRetryPolicy);
}
@Override
public DatabaseAccount getLatestDatabaseAccount() {
return this.globalEndpointManager.getLatestDatabaseAccount();
}
private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Getting Database Account");
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read,
ResourceType.DatabaseAccount, "",
(HashMap<String, String>) null,
null);
return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount);
} catch (Exception e) {
logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Object getSession() {
return this.sessionContainer;
}
public void setSession(Object sessionContainer) {
this.sessionContainer = (SessionContainer) sessionContainer;
}
@Override
public RxClientCollectionCache getCollectionCache() {
return this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return partitionKeyRangeCache;
}
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
return Flux.defer(() -> {
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null);
return this.populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
requestPopulated.setEndpointOverride(endpoint);
return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> {
String message = String.format("Failed to retrieve database account information. %s",
e.getCause() != null
? e.getCause().toString()
: e.toString());
logger.warn(message);
}).map(rsp -> rsp.getResource(DatabaseAccount.class))
.doOnNext(databaseAccount ->
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled()
&& BridgeInternal.isEnableMultipleWriteLocations(databaseAccount));
});
});
}
/**
* Certain requests must be routed through gateway even when the client connectivity mode is direct.
*
* @param request
* @return RxStoreModel
*/
private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) {
if (request.UseGatewayMode) {
return this.gatewayProxy;
}
ResourceType resourceType = request.getResourceType();
OperationType operationType = request.getOperationType();
if (resourceType == ResourceType.Offer ||
resourceType == ResourceType.ClientEncryptionKey ||
resourceType.isScript() && operationType != OperationType.ExecuteJavaScript ||
resourceType == ResourceType.PartitionKeyRange ||
resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) {
return this.gatewayProxy;
}
if (operationType == OperationType.Create
|| operationType == OperationType.Upsert) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection ||
resourceType == ResourceType.Permission) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Delete) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Replace) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Read) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else {
if ((operationType == OperationType.Query ||
operationType == OperationType.SqlQuery ||
operationType == OperationType.ReadFeed) &&
Utils.isCollectionChild(request.getResourceType())) {
if (request.getPartitionKeyRangeIdentity() == null &&
request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) {
return this.gatewayProxy;
}
}
return this.storeModel;
}
}
@Override
public void close() {
logger.info("Attempting to close client {}", this.clientId);
if (!closed.getAndSet(true)) {
this.activeClientsCnt.decrementAndGet();
logger.info("Shutting down ...");
logger.info("Closing Global Endpoint Manager ...");
LifeCycleUtils.closeQuietly(this.globalEndpointManager);
logger.info("Closing StoreClientFactory ...");
LifeCycleUtils.closeQuietly(this.storeClientFactory);
logger.info("Shutting down reactorHttpClient ...");
LifeCycleUtils.closeQuietly(this.reactorHttpClient);
logger.info("Shutting down CpuMonitor ...");
CpuMemoryMonitor.unregister(this);
if (this.throughputControlEnabled.get()) {
logger.info("Closing ThroughputControlStore ...");
this.throughputControlStore.close();
}
logger.info("Shutting down completed.");
} else {
logger.warn("Already shutdown!");
}
}
@Override
public ItemDeserializer getItemDeserializer() {
return this.itemDeserializer;
}
@Override
public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group can not be null");
if (this.throughputControlEnabled.compareAndSet(false, true)) {
this.throughputControlStore =
new ThroughputControlStore(
this.collectionCache,
this.connectionPolicy.getConnectionMode(),
this.partitionKeyRangeCache);
this.storeModel.enableThroughputControl(throughputControlStore);
}
this.throughputControlStore.enableThroughputControlGroup(group);
}
private static SqlQuerySpec createLogicalPartitionScanQuerySpec(
PartitionKey partitionKey,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE");
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey);
String pkParamName = "@pkValue";
parameters.add(new SqlParameter(pkParamName, pkValue));
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
@Override
public Mono<List<FeedRange>> getFeedRanges(String collectionLink) {
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
collectionLink,
new HashMap<>());
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null);
invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request);
return ObservableHelper.inlineIfPossibleAsObs(
() -> getFeedRangesInternal(request, collectionLink),
invalidPartitionExceptionRetryPolicy);
}
private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) {
logger.debug("getFeedRange collectionLink=[{}]", collectionLink);
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null,
request);
return collectionObs.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache
.tryGetOverlappingRangesAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null);
return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request));
});
}
private static List<FeedRange> toFeedRanges(
Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) {
final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v;
if (partitionKeyRangeList == null) {
request.forceNameCacheRefresh = true;
throw new InvalidPartitionException();
}
List<FeedRange> feedRanges = new ArrayList<>();
partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange)));
return feedRanges;
}
private static FeedRange toFeedRange(PartitionKeyRange pkRange) {
return new FeedRangeEpkImpl(pkRange.toRange());
}
} | class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener,
DiagnosticsClientContext {
private static final String tempMachineId = "uuid:" + UUID.randomUUID();
private static final AtomicInteger activeClientsCnt = new AtomicInteger(0);
private static final AtomicInteger clientIdGenerator = new AtomicInteger(0);
private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>(
PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey,
PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false);
private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " +
"ParallelDocumentQueryExecutioncontext, but not used";
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper();
private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer();
private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class);
private final String masterKeyOrResourceToken;
private final URI serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel consistencyLevel;
private final BaseAuthorizationTokenProvider authorizationTokenProvider;
private final UserAgentContainer userAgentContainer;
private final boolean hasAuthKeyResourceToken;
private final Configs configs;
private final boolean connectionSharingAcrossClientsEnabled;
private AzureKeyCredential credential;
private final TokenCredential tokenCredential;
private String[] tokenCredentialScopes;
private SimpleTokenCache tokenCredentialCache;
private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver;
AuthorizationTokenType authorizationTokenType;
private SessionContainer sessionContainer;
private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY;
private RxClientCollectionCache collectionCache;
private RxStoreModel gatewayProxy;
private RxStoreModel storeModel;
private GlobalAddressResolver addressResolver;
private RxPartitionKeyRangeCache partitionKeyRangeCache;
private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap;
private final boolean contentResponseOnWriteEnabled;
private Map<String, PartitionedQueryExecutionInfo> queryPlanCache;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final int clientId;
private ClientTelemetry clientTelemetry;
private ApiType apiType;
private IRetryPolicyFactory resetSessionTokenRetryPolicy;
/**
* Compatibility mode: Allows to specify compatibility mode used by client when
* making query requests. Should be removed when application/sql is no longer
* supported.
*/
private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default;
private final GlobalEndpointManager globalEndpointManager;
private final RetryPolicy retryPolicy;
private HttpClient reactorHttpClient;
private Function<HttpClient, HttpClient> httpClientInterceptor;
private volatile boolean useMultipleWriteLocations;
private StoreClientFactory storeClientFactory;
private GatewayServiceConfigurationReader gatewayConfigurationReader;
private final DiagnosticsClientConfig diagnosticsClientConfig;
private final AtomicBoolean throughputControlEnabled;
private ThroughputControlStore throughputControlStore;
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
private RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
if (permissionFeed != null && permissionFeed.size() > 0) {
this.resourceTokensMap = new HashMap<>();
for (Permission permission : permissionFeed) {
String[] segments = StringUtils.split(permission.getResourceLink(),
Constants.Properties.PATH_SEPARATOR.charAt(0));
if (segments.length <= 0) {
throw new IllegalArgumentException("resourceLink");
}
List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null;
PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false);
if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) {
throw new IllegalArgumentException(permission.getResourceLink());
}
partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName);
if (partitionKeyAndResourceTokenPairs == null) {
partitionKeyAndResourceTokenPairs = new ArrayList<>();
this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs);
}
PartitionKey partitionKey = permission.getResourcePartitionKey();
partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair(
partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty,
permission.getToken()));
logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]",
pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken());
}
if(this.resourceTokensMap.isEmpty()) {
throw new IllegalArgumentException("permissionFeed");
}
String firstToken = permissionFeed.get(0).getToken();
if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) {
this.firstResourceTokenFromPermissionFeed = firstToken;
}
}
}
RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
activeClientsCnt.incrementAndGet();
this.clientId = clientIdGenerator.incrementAndGet();
this.diagnosticsClientConfig = new DiagnosticsClientConfig();
this.diagnosticsClientConfig.withClientId(this.clientId);
this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt);
this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled);
this.diagnosticsClientConfig.withConsistency(consistencyLevel);
this.throughputControlEnabled = new AtomicBoolean(false);
logger.info(
"Initializing DocumentClient [{}] with"
+ " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]",
this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol());
try {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
this.configs = configs;
this.masterKeyOrResourceToken = masterKeyOrResourceToken;
this.serviceEndpoint = serviceEndpoint;
this.credential = credential;
this.tokenCredential = tokenCredential;
this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled;
this.authorizationTokenType = AuthorizationTokenType.Invalid;
if (this.credential != null) {
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.authorizationTokenProvider = null;
hasAuthKeyResourceToken = true;
this.authorizationTokenType = AuthorizationTokenType.ResourceToken;
} else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken);
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else {
hasAuthKeyResourceToken = false;
this.authorizationTokenProvider = null;
if (tokenCredential != null) {
this.tokenCredentialScopes = new String[] {
serviceEndpoint.getScheme() + ":
};
this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential
.getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes)));
this.authorizationTokenType = AuthorizationTokenType.AadToken;
}
}
if (connectionPolicy != null) {
this.connectionPolicy = connectionPolicy;
} else {
this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig());
}
this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode());
this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled());
this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled());
this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions());
this.diagnosticsClientConfig.withMachineId(tempMachineId);
boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled);
this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing);
this.consistencyLevel = consistencyLevel;
this.userAgentContainer = new UserAgentContainer();
String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix();
if (userAgentSuffix != null && userAgentSuffix.length() > 0) {
userAgentContainer.setSuffix(userAgentSuffix);
}
this.httpClientInterceptor = null;
this.reactorHttpClient = httpClient();
this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs);
this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy);
this.resetSessionTokenRetryPolicy = retryPolicy;
CpuMemoryMonitor.register(this);
this.queryPlanCache = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE));
this.apiType = apiType;
} catch (RuntimeException e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
}
@Override
public DiagnosticsClientConfig getConfig() {
return diagnosticsClientConfig;
}
@Override
public CosmosDiagnostics createDiagnostics() {
return BridgeInternal.createCosmosDiagnostics(this, this.globalEndpointManager);
}
private void initializeGatewayConfigurationReader() {
this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager);
DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount();
if (databaseAccount == null) {
logger.error("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
throw new RuntimeException("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
}
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount);
}
private void updateGatewayProxy() {
((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader);
((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache);
((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache);
((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations);
}
public void serialize(CosmosClientMetadataCachesSnapshot state) {
RxCollectionCache.serialize(state, this.collectionCache);
}
private void initializeDirectConnectivity() {
this.addressResolver = new GlobalAddressResolver(this,
this.reactorHttpClient,
this.globalEndpointManager,
this.configs.getProtocol(),
this,
this.collectionCache,
this.partitionKeyRangeCache,
userAgentContainer,
null,
this.connectionPolicy,
this.apiType);
this.storeClientFactory = new StoreClientFactory(
this.addressResolver,
this.diagnosticsClientConfig,
this.configs,
this.connectionPolicy,
this.userAgentContainer,
this.connectionSharingAcrossClientsEnabled,
this.clientTelemetry
);
this.createStoreModel(true);
}
DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() {
return new DatabaseAccountManagerInternal() {
@Override
public URI getServiceEndpoint() {
return RxDocumentClientImpl.this.getServiceEndpoint();
}
@Override
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
logger.info("Getting database account endpoint from {}", endpoint);
return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return RxDocumentClientImpl.this.getConnectionPolicy();
}
};
}
RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer,
ConsistencyLevel consistencyLevel,
QueryCompatibilityMode queryCompatibilityMode,
UserAgentContainer userAgentContainer,
GlobalEndpointManager globalEndpointManager,
HttpClient httpClient,
ApiType apiType) {
return new RxGatewayStoreModel(
this,
sessionContainer,
consistencyLevel,
queryCompatibilityMode,
userAgentContainer,
globalEndpointManager,
httpClient,
apiType);
}
private HttpClient httpClient() {
HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs)
.withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout())
.withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize())
.withProxy(this.connectionPolicy.getProxy())
.withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout());
if (connectionSharingAcrossClientsEnabled) {
return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig);
} else {
diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig);
return HttpClient.createFixed(httpClientConfig);
}
}
private void createStoreModel(boolean subscribeRntbdStatus) {
StoreClient storeClient = this.storeClientFactory.createStoreClient(this,
this.addressResolver,
this.sessionContainer,
this.gatewayConfigurationReader,
this,
this.useMultipleWriteLocations
);
this.storeModel = new ServerStoreModel(storeClient);
}
@Override
public URI getServiceEndpoint() {
return this.serviceEndpoint;
}
@Override
public URI getWriteEndpoint() {
return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null);
}
@Override
public URI getReadEndpoint() {
return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return this.connectionPolicy;
}
@Override
public boolean isContentResponseOnWriteEnabled() {
return contentResponseOnWriteEnabled;
}
@Override
public ConsistencyLevel getConsistencyLevel() {
return consistencyLevel;
}
@Override
public ClientTelemetry getClientTelemetry() {
return this.clientTelemetry;
}
@Override
public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (database == null) {
throw new IllegalArgumentException("Database");
}
logger.debug("Creating a Database. id: [{}]", database.getId());
validateResource(database);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Reading a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT);
}
private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) {
switch (resourceTypeEnum) {
case Database:
return Paths.DATABASES_ROOT;
case DocumentCollection:
return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT);
case Document:
return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT);
case Offer:
return Paths.OFFERS_ROOT;
case User:
return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT);
case ClientEncryptionKey:
return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
case Permission:
return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT);
case Attachment:
return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT);
case StoredProcedure:
return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
case Trigger:
return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT);
case UserDefinedFunction:
return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
case Conflict:
return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT);
default:
throw new IllegalArgumentException("resource type not supported");
}
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) {
if (options == null) {
return null;
}
return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options);
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) {
if (options == null) {
return null;
}
return options.getOperationContextAndListenerTuple();
}
private <T extends Resource> Flux<FeedResponse<T>> createQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum) {
String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum);
UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getCorrelationActivityId(options);
UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ?
correlationActivityIdOfRequestOptions : Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this,
getOperationContextAndListenerTuple(options));
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> createQueryInternal(
resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId),
invalidPartitionExceptionRetryPolicy);
}
private <T extends Resource> Flux<FeedResponse<T>> createQueryInternal(
String resourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
IDocumentQueryClient queryClient,
UUID activityId) {
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory
.createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery,
options, resourceLink, false, activityId,
Configs.isQueryPlanCachingEnabled(), queryPlanCache);
AtomicBoolean isFirstResponse = new AtomicBoolean(true);
return executionContext.flatMap(iDocumentQueryExecutionContext -> {
QueryInfo queryInfo = null;
if (iDocumentQueryExecutionContext instanceof PipelinedDocumentQueryExecutionContext) {
queryInfo = ((PipelinedDocumentQueryExecutionContext<T>) iDocumentQueryExecutionContext).getQueryInfo();
}
QueryInfo finalQueryInfo = queryInfo;
return iDocumentQueryExecutionContext.executeAsync()
.map(tFeedResponse -> {
if (finalQueryInfo != null) {
if (finalQueryInfo.hasSelectValue()) {
ModelBridgeInternal
.addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo);
}
if (isFirstResponse.compareAndSet(true, false)) {
ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse,
finalQueryInfo.getQueryPlanDiagnosticsContext());
}
}
return tFeedResponse;
});
});
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) {
return queryDatabases(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database);
}
@Override
public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink,
DocumentCollection collection, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink,
DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink,
collection.getId());
validateResource(collection);
String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
});
} catch (Exception e) {
logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Replacing a Collection. id: [{}]", collection.getId());
validateResource(collection);
String path = Utils.joinPath(collection.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
if (resourceResponse.getResource() != null) {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
}
});
} catch (Exception e) {
logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.DELETE)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated));
}
private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated ->
this.getStoreProxy(requestPopulated).processMessage(requestPopulated)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
));
}
@Override
public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class,
Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection);
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection);
}
private static String serializeProcedureParams(List<Object> objectArray) {
String[] stringArray = new String[objectArray.size()];
for (int i = 0; i < objectArray.size(); ++i) {
Object object = objectArray.get(i);
if (object instanceof JsonSerializable) {
stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object);
} else {
try {
stringArray[i] = mapper.writeValueAsString(object);
} catch (IOException e) {
throw new IllegalArgumentException("Can't serialize the object into the json string", e);
}
}
}
return String.format("[%s]", StringUtils.join(stringArray, ","));
}
private static void validateResource(Resource resource) {
if (!StringUtils.isEmpty(resource.getId())) {
if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 ||
resource.getId().indexOf('?') != -1 || resource.getId().indexOf('
throw new IllegalArgumentException("Id contains illegal chars.");
}
if (resource.getId().endsWith(" ")) {
throw new IllegalArgumentException("Id ends with a space.");
}
}
}
private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) {
Map<String, String> headers = new HashMap<>();
if (this.useMultipleWriteLocations) {
headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString());
}
if (consistencyLevel != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString());
}
if (options == null) {
if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
return headers;
}
Map<String, String> customOptions = options.getHeaders();
if (customOptions != null) {
headers.putAll(customOptions);
}
boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled;
if (options.isContentResponseOnWriteEnabled() != null) {
contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled();
}
if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
if (options.getIfMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag());
}
if(options.getIfNoneMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag());
}
if (options.getConsistencyLevel() != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString());
}
if (options.getIndexingDirective() != null) {
headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString());
}
if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) {
String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude);
}
if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) {
String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude);
}
if (!Strings.isNullOrEmpty(options.getSessionToken())) {
headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken());
}
if (options.getResourceTokenExpirySeconds() != null) {
headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY,
String.valueOf(options.getResourceTokenExpirySeconds()));
}
if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString());
} else if (options.getOfferType() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType());
}
if (options.getOfferThroughput() == null) {
if (options.getThroughputProperties() != null) {
Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties());
final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings();
OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null;
if (offerAutoscaleSettings != null) {
autoscaleAutoUpgradeProperties
= offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties();
}
if (offer.hasOfferThroughput() &&
(offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 ||
autoscaleAutoUpgradeProperties != null &&
autoscaleAutoUpgradeProperties
.getAutoscaleThroughputProperties()
.getIncrementPercent() >= 0)) {
throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with "
+ "fixed offer");
}
if (offer.hasOfferThroughput()) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput()));
} else if (offer.getOfferAutoScaleSettings() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS,
ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings()));
}
}
}
if (options.isQuotaInfoEnabled()) {
headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true));
}
if (options.isScriptLoggingEnabled()) {
headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true));
}
if (options.getDedicatedGatewayRequestOptions() != null &&
options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) {
headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS,
String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions())));
}
return headers;
}
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return this.resetSessionTokenRetryPolicy;
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Document document,
RequestOptions options) {
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs
.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object document,
RequestOptions options,
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) {
return collectionObs.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private void addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object objectDoc, RequestOptions options,
DocumentCollection collection) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
PartitionKeyInternal partitionKeyInternal = null;
if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else if (options != null && options.getPartitionKey() != null) {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey());
} else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) {
partitionKeyInternal = PartitionKeyInternal.getEmpty();
} else if (contentAsByteBuffer != null || objectDoc != null) {
InternalObjectNode internalObjectNode;
if (objectDoc instanceof InternalObjectNode) {
internalObjectNode = (InternalObjectNode) objectDoc;
} else if (objectDoc instanceof ObjectNode) {
internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc);
} else if (contentAsByteBuffer != null) {
contentAsByteBuffer.rewind();
internalObjectNode = new InternalObjectNode(contentAsByteBuffer);
} else {
throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null");
}
Instant serializationStartTime = Instant.now();
partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTime,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION
);
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
} else {
throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation.");
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
}
public static PartitionKeyInternal extractPartitionKeyValueFromDocument(
InternalObjectNode document,
PartitionKeyDefinition partitionKeyDefinition) {
if (partitionKeyDefinition != null) {
switch (partitionKeyDefinition.getKind()) {
case HASH:
String path = partitionKeyDefinition.getPaths().iterator().next();
List<String> parts = PathParser.getPathParts(path);
if (parts.size() >= 1) {
Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts);
if (value == null || value.getClass() == ObjectNode.class) {
value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
}
if (value instanceof PartitionKeyInternal) {
return (PartitionKeyInternal) value;
} else {
return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false);
}
}
break;
case MULTI_HASH:
Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()];
for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){
String partitionPath = partitionKeyDefinition.getPaths().get(pathIter);
List<String> partitionPathParts = PathParser.getPathParts(partitionPath);
partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts);
}
return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false);
default:
throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind());
}
}
return null;
}
private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
Object document,
RequestOptions options,
boolean disableAutomaticIdGeneration,
OperationType operationType) {
if (StringUtils.isEmpty(documentCollectionLink)) {
throw new IllegalArgumentException("documentCollectionLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Document, path, requestHeaders, options, content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return addPartitionKeyInformation(request, content, document, options, collectionObs);
}
private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink");
checkNotNull(serverBatchRequest, "expected non null serverBatchRequest");
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody()));
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Batch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> {
addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v);
return request;
});
}
private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request,
ServerBatchRequest serverBatchRequest,
DocumentCollection collection) {
if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) {
PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue();
PartitionKeyInternal partitionKeyInternal;
if (partitionKey.equals(PartitionKey.NONE)) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey);
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
} else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) {
request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId()));
} else {
throw new UnsupportedOperationException("Unknown Server request.");
}
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString());
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch()));
request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError()));
request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size());
return request;
}
private Mono<RxDocumentServiceRequest> populateHeaders(RxDocumentServiceRequest request, RequestVerb httpMethod) {
request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123());
if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null
|| this.cosmosAuthorizationTokenResolver != null || this.credential != null) {
String resourceName = request.getResourceAddress();
String authorization = this.getUserAuthorizationToken(
resourceName, request.getResourceType(), httpMethod, request.getHeaders(),
AuthorizationTokenType.PrimaryMasterKey, request.properties);
try {
authorization = URLEncoder.encode(authorization, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Failed to encode authtoken.", e);
}
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
}
if (this.apiType != null) {
request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString());
}
if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod))
&& !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
}
if (RequestVerb.PATCH.equals(httpMethod) &&
!request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH);
}
if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) {
request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
}
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
if (this.requiresFeedRangeFiltering(request)) {
return request.getFeedRange()
.populateFeedRangeFilteringHeaders(
this.getPartitionKeyRangeCache(),
request,
this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request))
.flatMap(this::populateAuthorizationHeader);
}
return this.populateAuthorizationHeader(request);
}
private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) {
if (request.getResourceType() != ResourceType.Document &&
request.getResourceType() != ResourceType.Conflict) {
return false;
}
switch (request.getOperationType()) {
case ReadFeed:
case Query:
case SqlQuery:
return request.getFeedRange() != null;
default:
return false;
}
}
@Override
public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) {
if (request == null) {
throw new IllegalArgumentException("request");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return request;
});
} else {
return Mono.just(request);
}
}
@Override
public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) {
if (httpHeaders == null) {
throw new IllegalArgumentException("httpHeaders");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return httpHeaders;
});
}
return Mono.just(httpHeaders);
}
@Override
public AuthorizationTokenType getAuthorizationTokenType() {
return this.authorizationTokenType;
}
@Override
public String getUserAuthorizationToken(String resourceName,
ResourceType resourceType,
RequestVerb requestVerb,
Map<String, String> headers,
AuthorizationTokenType tokenType,
Map<String, Object> properties) {
if (this.cosmosAuthorizationTokenResolver != null) {
return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(),
properties != null ? Collections.unmodifiableMap(properties) : null);
} else if (credential != null) {
return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName,
resourceType, headers);
} else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) {
return masterKeyOrResourceToken;
} else {
assert resourceTokensMap != null;
if(resourceType.equals(ResourceType.DatabaseAccount)) {
return this.firstResourceTokenFromPermissionFeed;
}
return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers);
}
}
private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) {
CosmosResourceType cosmosResourceType =
ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString());
if (cosmosResourceType == null) {
return CosmosResourceType.SYSTEM;
}
return cosmosResourceType;
}
void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) {
this.sessionContainer.setSessionToken(request, response.getResponseHeaders());
}
private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
Map<String, String> headers = requestPopulated.getHeaders();
assert (headers != null);
headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true");
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
);
});
}
private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.PUT)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PATCH);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(request).processMessage(request);
}
@Override
public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) {
try {
logger.debug("Creating a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Create);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance);
}
private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Upsert);
Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = Utils.getCollectionName(documentLink);
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Document typedDocument = documentFromObject(document, mapper);
return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = document.getSelfLink();
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (document == null) {
throw new IllegalArgumentException("document");
}
return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a database due to [{}]", e.getMessage());
return Mono.error(e);
}
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink,
Document document,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
if (document == null) {
throw new IllegalArgumentException("document");
}
logger.debug("Replacing a Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = serializeJsonToByteBuffer(document);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs);
return requestObs.flatMap(req -> replace(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> patchDocument(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink");
checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations");
logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options));
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Patch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(
request,
null,
null,
options,
collectionObs);
return requestObs.flatMap(req -> patch(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy);
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Deleting a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs);
return requestObs.flatMap(req -> this
.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> this
.deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting documents due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Reading a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> {
return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Document>> readDocuments(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return queryDocuments(collectionLink, "SELECT * FROM r", options);
}
@Override
public <T> Mono<FeedResponse<T>> readMany(
List<CosmosItemIdentity> itemIdentityList,
String collectionLink,
CosmosQueryRequestOptions options,
Class<T> klass) {
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink, null
);
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request);
return collectionObs
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache
.tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null);
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap =
new HashMap<>();
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
itemIdentityList
.forEach(itemIdentity -> {
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(
itemIdentity.getPartitionKey()),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
if (partitionRangeItemKeyMap.get(range) == null) {
List<CosmosItemIdentity> list = new ArrayList<>();
list.add(itemIdentity);
partitionRangeItemKeyMap.put(range, list);
} else {
List<CosmosItemIdentity> pairs =
partitionRangeItemKeyMap.get(range);
pairs.add(itemIdentity);
partitionRangeItemKeyMap.put(range, pairs);
}
});
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap;
rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap,
collection.getPartitionKey());
return createReadManyQuery(
resourceLink,
new SqlQuerySpec(DUMMY_SQL_QUERY),
options,
Document.class,
ResourceType.Document,
collection,
Collections.unmodifiableMap(rangeQueryMap))
.collectList()
.map(feedList -> {
List<T> finalList = new ArrayList<>();
HashMap<String, String> headers = new HashMap<>();
ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>();
double requestCharge = 0;
for (FeedResponse<Document> page : feedList) {
ConcurrentMap<String, QueryMetrics> pageQueryMetrics =
ModelBridgeInternal.queryMetrics(page);
if (pageQueryMetrics != null) {
pageQueryMetrics.forEach(
aggregatedQueryMetrics::putIfAbsent);
}
requestCharge += page.getRequestCharge();
finalList.addAll(page.getResults().stream().map(document ->
ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList()));
}
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double
.toString(requestCharge));
FeedResponse<T> frp = BridgeInternal
.createFeedResponse(finalList, headers);
return frp;
});
});
}
);
}
private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap(
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap,
PartitionKeyDefinition partitionKeyDefinition) {
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>();
String partitionKeySelector = createPkSelector(partitionKeyDefinition);
for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) {
SqlQuerySpec sqlQuerySpec;
if (partitionKeySelector.equals("[\"id\"]")) {
sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector);
} else {
sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector);
}
rangeQueryMap.put(entry.getKey(), sqlQuerySpec);
}
return rangeQueryMap;
}
private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(
List<CosmosItemIdentity> idPartitionKeyPairList,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( ");
for (int i = 0; i < idPartitionKeyPairList.size(); i++) {
CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i);
String idValue = itemIdentity.getId();
String idParamName = "@param" + i;
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
if (!Objects.equals(idValue, pkValue)) {
continue;
}
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append(idParamName);
if (i < idPartitionKeyPairList.size() - 1) {
queryStringBuilder.append(", ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE ( ");
for (int i = 0; i < itemIdentities.size(); i++) {
CosmosItemIdentity itemIdentity = itemIdentities.get(i);
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
String pkParamName = "@param" + (2 * i);
parameters.add(new SqlParameter(pkParamName, pkValue));
String idValue = itemIdentity.getId();
String idParamName = "@param" + (2 * i + 1);
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append("(");
queryStringBuilder.append("c.id = ");
queryStringBuilder.append(idParamName);
queryStringBuilder.append(" AND ");
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
queryStringBuilder.append(" )");
if (i < itemIdentities.size() - 1) {
queryStringBuilder.append(" OR ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) {
return partitionKeyDefinition.getPaths()
.stream()
.map(pathPart -> StringUtils.substring(pathPart, 1))
.map(pathPart -> StringUtils.replace(pathPart, "\"", "\\"))
.map(part -> "[\"" + part + "\"]")
.collect(Collectors.joining());
}
private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
DocumentCollection collection,
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) {
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(),
sqlQuery,
rangeQueryMap,
options,
collection.getResourceId(),
parentResourceLink,
activityId,
klass,
resourceTypeEnum);
return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync);
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, String query, CosmosQueryRequestOptions options) {
return queryDocuments(collectionLink, new SqlQuerySpec(query), options);
}
private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return new IDocumentQueryClient () {
@Override
public RxCollectionCache getCollectionCache() {
return RxDocumentClientImpl.this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return RxDocumentClientImpl.this.partitionKeyRangeCache;
}
@Override
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy;
}
@Override
public ConsistencyLevel getDefaultConsistencyLevelAsync() {
return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel();
}
@Override
public ConsistencyLevel getDesiredConsistencyLevelAsync() {
return RxDocumentClientImpl.this.consistencyLevel;
}
@Override
public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) {
if (operationContextAndListenerTuple == null) {
return RxDocumentClientImpl.this.query(request).single();
} else {
final OperationListener listener =
operationContextAndListenerTuple.getOperationListener();
final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext();
request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId());
listener.requestListener(operationContext, request);
return RxDocumentClientImpl.this.query(request).single().doOnNext(
response -> listener.responseListener(operationContext, response)
).doOnError(
ex -> listener.exceptionListener(operationContext, ex)
);
}
}
@Override
public QueryCompatibilityMode getQueryCompatibilityMode() {
return QueryCompatibilityMode.Default;
}
@Override
public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) {
return null;
}
};
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
SqlQuerySpecLogger.getInstance().logQuery(querySpec);
return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document);
}
@Override
public Flux<FeedResponse<Document>> queryDocumentChangeFeed(
final DocumentCollection collection,
final CosmosChangeFeedRequestOptions changeFeedOptions) {
checkNotNull(collection, "Argument 'collection' must not be null.");
ChangeFeedQueryImpl<Document> changeFeedQueryImpl = new ChangeFeedQueryImpl<>(
this,
ResourceType.Document,
Document.class,
collection.getAltLink(),
collection.getResourceId(),
changeFeedOptions);
return changeFeedQueryImpl.executeAsync();
}
@Override
public Flux<FeedResponse<Document>> readAllDocuments(
String collectionLink,
PartitionKey partitionKey,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (partitionKey == null) {
throw new IllegalArgumentException("partitionKey");
}
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null
);
Flux<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request).flux();
return collectionObs.flatMap(documentCollectionResourceResponse -> {
DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
String pkSelector = createPkSelector(pkDefinition);
SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector);
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
final CosmosQueryRequestOptions effectiveOptions =
ModelBridgeInternal.createQueryRequestOptions(options);
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> {
Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache
.tryLookupAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null).flux();
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(partitionKey),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
return createQueryInternal(
resourceLink,
querySpec,
ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()),
Document.class,
ResourceType.Document,
queryClient,
activityId);
});
},
invalidPartitionExceptionRetryPolicy);
});
}
@Override
public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() {
return queryPlanCache;
}
@Override
public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class,
Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT));
}
private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
validateResource(storedProcedure);
String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType,
ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
return request;
}
private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (udf == null) {
throw new IllegalArgumentException("udf");
}
validateResource(udf);
String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Create);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId());
RxDocumentClientImpl.validateResource(storedProcedure);
String path = Utils.joinPath(storedProcedure.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class,
Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
List<Object> procedureParams) {
return this.executeStoredProcedure(storedProcedureLink, null, procedureParams);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy);
}
@Override
public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy);
}
private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) {
try {
logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript);
requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ExecuteJavaScript,
ResourceType.StoredProcedure, path,
procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "",
requestHeaders, options);
if (retryPolicy != null) {
retryPolicy.onBeforeSendRequest(request);
}
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options))
.map(response -> {
this.captureSessionToken(request, response);
return toStoredProcedureResponse(response);
}));
} catch (Exception e) {
logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
DocumentClientRetryPolicy requestRetryPolicy,
boolean disableAutomaticIdGeneration) {
try {
logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size());
Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true));
} catch (Exception ex) {
logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex);
return Mono.error(ex);
}
}
@Override
public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path,
trigger, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId());
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(trigger.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Trigger, Trigger.class,
Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryTriggers(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger);
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (udf == null) {
throw new IllegalArgumentException("udf");
}
logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId());
validateResource(udf);
String path = Utils.joinPath(udf.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class,
Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
String query, CosmosQueryRequestOptions options) {
return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction);
}
@Override
public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Conflict, Conflict.class,
Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryConflicts(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict);
}
@Override
public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (user == null) {
throw new IllegalArgumentException("user");
}
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.User, path, user, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (user == null) {
throw new IllegalArgumentException("user");
}
logger.debug("Replacing a User. user id [{}]", user.getId());
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(user.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.User, path, user, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Deleting a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Reading a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.User, User.class,
Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) {
return queryUsers(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User);
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(clientEncryptionKeyLink)) {
throw new IllegalArgumentException("clientEncryptionKeyLink");
}
logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink);
String path = Utils.joinPath(clientEncryptionKeyLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink,
ClientEncryptionKey clientEncryptionKey, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId());
RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey,
String nameBasedLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey,
nameBasedLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId());
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(nameBasedLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey,
OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders,
options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class,
Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey);
}
@Override
public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy());
}
private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
if (permission == null) {
throw new IllegalArgumentException("permission");
}
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Permission, path, permission, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (permission == null) {
throw new IllegalArgumentException("permission");
}
logger.debug("Replacing a Permission. permission id [{}]", permission.getId());
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(permission.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Reading a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
return readFeed(options, ResourceType.Permission, Permission.class,
Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query,
CosmosQueryRequestOptions options) {
return queryPermissions(userLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission);
}
@Override
public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
if (offer == null) {
throw new IllegalArgumentException("offer");
}
logger.debug("Replacing an Offer. offer id [{}]", offer.getId());
RxDocumentClientImpl.validateResource(offer);
String path = Utils.joinPath(offer.getSelfLink(), null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace,
ResourceType.Offer, path, offer, null, null);
return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Offer>> readOffer(String offerLink) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(offerLink)) {
throw new IllegalArgumentException("offerLink");
}
logger.debug("Reading an Offer. offerLink [{}]", offerLink);
String path = Utils.joinPath(offerLink, null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Offer, Offer.class,
Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null));
}
private <T extends Resource> Flux<FeedResponse<T>> readFeed(CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options);
int maxPageSize = maxItemCount != null ? maxItemCount : -1;
final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options;
DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> {
Map<String, String> requestHeaders = new HashMap<>();
if (continuationToken != null) {
requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken);
}
requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize));
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions);
retryPolicy.onBeforeSendRequest(request);
return request;
};
Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper
.inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)),
retryPolicy);
return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, maxPageSize);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) {
return queryOffers(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer);
}
@Override
public Mono<DatabaseAccount> getDatabaseAccount() {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy),
documentClientRetryPolicy);
}
@Override
public DatabaseAccount getLatestDatabaseAccount() {
return this.globalEndpointManager.getLatestDatabaseAccount();
}
private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Getting Database Account");
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read,
ResourceType.DatabaseAccount, "",
(HashMap<String, String>) null,
null);
return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount);
} catch (Exception e) {
logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Object getSession() {
return this.sessionContainer;
}
public void setSession(Object sessionContainer) {
this.sessionContainer = (SessionContainer) sessionContainer;
}
@Override
public RxClientCollectionCache getCollectionCache() {
return this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return partitionKeyRangeCache;
}
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
return Flux.defer(() -> {
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null);
return this.populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
requestPopulated.setEndpointOverride(endpoint);
return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> {
String message = String.format("Failed to retrieve database account information. %s",
e.getCause() != null
? e.getCause().toString()
: e.toString());
logger.warn(message);
}).map(rsp -> rsp.getResource(DatabaseAccount.class))
.doOnNext(databaseAccount ->
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled()
&& BridgeInternal.isEnableMultipleWriteLocations(databaseAccount));
});
});
}
/**
* Certain requests must be routed through gateway even when the client connectivity mode is direct.
*
* @param request
* @return RxStoreModel
*/
private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) {
if (request.UseGatewayMode) {
return this.gatewayProxy;
}
ResourceType resourceType = request.getResourceType();
OperationType operationType = request.getOperationType();
if (resourceType == ResourceType.Offer ||
resourceType == ResourceType.ClientEncryptionKey ||
resourceType.isScript() && operationType != OperationType.ExecuteJavaScript ||
resourceType == ResourceType.PartitionKeyRange ||
resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) {
return this.gatewayProxy;
}
if (operationType == OperationType.Create
|| operationType == OperationType.Upsert) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection ||
resourceType == ResourceType.Permission) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Delete) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Replace) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Read) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else {
if ((operationType == OperationType.Query ||
operationType == OperationType.SqlQuery ||
operationType == OperationType.ReadFeed) &&
Utils.isCollectionChild(request.getResourceType())) {
if (request.getPartitionKeyRangeIdentity() == null &&
request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) {
return this.gatewayProxy;
}
}
return this.storeModel;
}
}
@Override
public void close() {
logger.info("Attempting to close client {}", this.clientId);
if (!closed.getAndSet(true)) {
activeClientsCnt.decrementAndGet();
logger.info("Shutting down ...");
logger.info("Closing Global Endpoint Manager ...");
LifeCycleUtils.closeQuietly(this.globalEndpointManager);
logger.info("Closing StoreClientFactory ...");
LifeCycleUtils.closeQuietly(this.storeClientFactory);
logger.info("Shutting down reactorHttpClient ...");
LifeCycleUtils.closeQuietly(this.reactorHttpClient);
logger.info("Shutting down CpuMonitor ...");
CpuMemoryMonitor.unregister(this);
if (this.throughputControlEnabled.get()) {
logger.info("Closing ThroughputControlStore ...");
this.throughputControlStore.close();
}
logger.info("Shutting down completed.");
} else {
logger.warn("Already shutdown!");
}
}
@Override
public ItemDeserializer getItemDeserializer() {
return this.itemDeserializer;
}
@Override
public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group can not be null");
if (this.throughputControlEnabled.compareAndSet(false, true)) {
this.throughputControlStore =
new ThroughputControlStore(
this.collectionCache,
this.connectionPolicy.getConnectionMode(),
this.partitionKeyRangeCache);
this.storeModel.enableThroughputControl(throughputControlStore);
}
this.throughputControlStore.enableThroughputControlGroup(group);
}
private static SqlQuerySpec createLogicalPartitionScanQuerySpec(
PartitionKey partitionKey,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE");
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey);
String pkParamName = "@pkValue";
parameters.add(new SqlParameter(pkParamName, pkValue));
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
@Override
public Mono<List<FeedRange>> getFeedRanges(String collectionLink) {
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
collectionLink,
new HashMap<>());
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null);
invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request);
return ObservableHelper.inlineIfPossibleAsObs(
() -> getFeedRangesInternal(request, collectionLink),
invalidPartitionExceptionRetryPolicy);
}
private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) {
logger.debug("getFeedRange collectionLink=[{}]", collectionLink);
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null,
request);
return collectionObs.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache
.tryGetOverlappingRangesAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null);
return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request));
});
}
private static List<FeedRange> toFeedRanges(
Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) {
final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v;
if (partitionKeyRangeList == null) {
request.forceNameCacheRefresh = true;
throw new InvalidPartitionException();
}
List<FeedRange> feedRanges = new ArrayList<>();
partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange)));
return feedRanges;
}
private static FeedRange toFeedRange(PartitionKeyRange pkRange) {
return new FeedRangeEpkImpl(pkRange.toRange());
}
} |
loadAzureVmMetaData is part of init and not meant to call multiple times , why we used AtomicReference here ? | private void loadAzureVmMetaData() {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null) {
this.populateAzureVmMetaData(metadataSnapshot);
return;
}
URI targetEndpoint = null;
try {
targetEndpoint = new URI(AZURE_VM_METADATA);
} catch (URISyntaxException ex) {
logger.info("Unable to parse azure vm metadata url");
return;
}
HashMap<String, String> headers = new HashMap<>();
headers.put("Metadata", "true");
HttpHeaders httpHeaders = new HttpHeaders(headers);
HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(),
httpHeaders);
Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest);
httpResponseMono
.flatMap(response -> response.bodyAsString()).map(metadataJson -> parse(metadataJson,
AzureVMMetadata.class)).doOnSuccess(metadata -> {
azureVmMetaDataSingleton.compareAndSet(null, metadata);
this.populateAzureVmMetaData(metadata);
}).onErrorResume(throwable -> {
logger.info("Client is not on azure vm");
logger.debug("Unable to get azure vm metadata", throwable);
return Mono.empty();
}).subscribe();
} | AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get(); | private void loadAzureVmMetaData() {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null) {
this.populateAzureVmMetaData(metadataSnapshot);
return;
}
URI targetEndpoint = null;
try {
targetEndpoint = new URI(AZURE_VM_METADATA);
} catch (URISyntaxException ex) {
logger.info("Unable to parse azure vm metadata url");
return;
}
HashMap<String, String> headers = new HashMap<>();
headers.put("Metadata", "true");
HttpHeaders httpHeaders = new HttpHeaders(headers);
HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(),
httpHeaders);
Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest);
httpResponseMono
.flatMap(response -> response.bodyAsString()).map(metadataJson -> parse(metadataJson,
AzureVMMetadata.class)).doOnSuccess(metadata -> {
azureVmMetaDataSingleton.compareAndSet(null, metadata);
this.populateAzureVmMetaData(metadata);
}).onErrorResume(throwable -> {
logger.info("Client is not on azure vm");
logger.debug("Unable to get azure vm metadata", throwable);
return Mono.empty();
}).subscribe();
} | class ClientTelemetry {
public final static int ONE_KB_TO_BYTES = 1024;
public final static int REQUEST_LATENCY_MAX_MILLI_SEC = 300000;
public final static int REQUEST_LATENCY_SUCCESS_PRECISION = 4;
public final static int REQUEST_LATENCY_FAILURE_PRECISION = 2;
public final static String REQUEST_LATENCY_NAME = "RequestLatency";
public final static String REQUEST_LATENCY_UNIT = "MilliSecond";
public final static int REQUEST_CHARGE_MAX = 10000;
public final static int REQUEST_CHARGE_PRECISION = 2;
public final static String REQUEST_CHARGE_NAME = "RequestCharge";
public final static String REQUEST_CHARGE_UNIT = "RU";
public final static String TCP_NEW_CHANNEL_LATENCY_NAME = "TcpNewChannelOpenLatency";
public final static String TCP_NEW_CHANNEL_LATENCY_UNIT = "MilliSecond";
public final static int TCP_NEW_CHANNEL_LATENCY_MAX_MILLI_SEC = 300000;
public final static int TCP_NEW_CHANNEL_LATENCY_PRECISION = 2;
public final static int CPU_MAX = 100;
public final static int CPU_PRECISION = 2;
private final static String CPU_NAME = "CPU";
private final static String CPU_UNIT = "Percentage";
public final static int MEMORY_MAX_IN_MB = 102400;
public final static int MEMORY_PRECISION = 2;
private final static String MEMORY_NAME = "MemoryRemaining";
private final static String MEMORY_UNIT = "MB";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final static AtomicLong instanceCount = new AtomicLong(0);
private final static AtomicReference<AzureVMMetadata> azureVmMetaDataSingleton =
new AtomicReference<>(null);
private ClientTelemetryInfo clientTelemetryInfo;
private final HttpClient httpClient;
private final ScheduledThreadPoolExecutor scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
new CosmosDaemonThreadFactory("ClientTelemetry-" + instanceCount.incrementAndGet()));
private final Scheduler scheduler = Schedulers.fromExecutor(scheduledExecutorService);
private static final Logger logger = LoggerFactory.getLogger(ClientTelemetry.class);
private volatile boolean isClosed;
private volatile boolean isClientTelemetryEnabled;
private static String AZURE_VM_METADATA = "http:
private static final double PERCENTILE_50 = 50.0;
private static final double PERCENTILE_90 = 90.0;
private static final double PERCENTILE_95 = 95.0;
private static final double PERCENTILE_99 = 99.0;
private static final double PERCENTILE_999 = 99.9;
private final int clientTelemetrySchedulingSec;
private final IAuthorizationTokenProvider tokenProvider;
private final String globalDatabaseAccountName;
public ClientTelemetry(DiagnosticsClientContext diagnosticsClientContext,
Boolean acceleratedNetworking,
String clientId,
String processId,
String userAgent,
ConnectionMode connectionMode,
String globalDatabaseAccountName,
String applicationRegion,
String hostEnvInfo,
HttpClient httpClient,
boolean isClientTelemetryEnabled,
IAuthorizationTokenProvider tokenProvider,
List<String> preferredRegions
) {
clientTelemetryInfo = new ClientTelemetryInfo(
getMachineId(diagnosticsClientContext),
clientId,
processId,
userAgent,
connectionMode,
globalDatabaseAccountName,
applicationRegion,
hostEnvInfo,
acceleratedNetworking,
preferredRegions);
this.isClosed = false;
this.httpClient = httpClient;
this.isClientTelemetryEnabled = isClientTelemetryEnabled;
this.clientTelemetrySchedulingSec = Configs.getClientTelemetrySchedulingInSec();
this.tokenProvider = tokenProvider;
this.globalDatabaseAccountName = globalDatabaseAccountName;
}
public ClientTelemetryInfo getClientTelemetryInfo() {
return clientTelemetryInfo;
}
public static String getMachineId(DiagnosticsClientContext diagnosticsClientContext) {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null && metadataSnapshot.getVmId() != null) {
String machineId = "vmId:" + metadataSnapshot.getVmId();
if (diagnosticsClientContext != null) {
diagnosticsClientContext.getConfig().withMachineId(machineId);
}
return machineId;
}
if (diagnosticsClientContext == null) {
return "";
}
return diagnosticsClientContext.getConfig().getMachineId();
}
public static void recordValue(ConcurrentDoubleHistogram doubleHistogram, long value) {
try {
doubleHistogram.recordValue(value);
} catch (Exception ex) {
logger.warn("Error while recording value for client telemetry. ", ex);
}
}
public static void recordValue(ConcurrentDoubleHistogram doubleHistogram, double value) {
try {
doubleHistogram.recordValue(value);
} catch (Exception ex) {
logger.warn("Error while recording value for client telemetry. ", ex);
}
}
public boolean isClientTelemetryEnabled() {
return isClientTelemetryEnabled;
}
public void init() {
loadAzureVmMetaData();
sendClientTelemetry().subscribe();
}
public void close() {
this.isClosed = true;
this.scheduledExecutorService.shutdown();
logger.debug("GlobalEndpointManager closed.");
}
private Mono<Void> sendClientTelemetry() {
return Mono.delay(Duration.ofSeconds(clientTelemetrySchedulingSec), CosmosSchedulers.COSMOS_PARALLEL)
.flatMap(t -> {
if (this.isClosed) {
logger.warn("client already closed");
return Mono.empty();
}
if (!Configs.isClientTelemetryEnabled(this.isClientTelemetryEnabled)) {
logger.trace("client telemetry not enabled");
return Mono.empty();
}
readHistogram();
try {
String endpoint = Configs.getClientTelemetryEndpoint();
if (StringUtils.isEmpty(endpoint)) {
logger.info("ClientTelemetry {}",
OBJECT_MAPPER.writeValueAsString(this.clientTelemetryInfo));
clearDataForNextRun();
return this.sendClientTelemetry();
} else {
URI targetEndpoint = new URI(endpoint);
ByteBuffer byteBuffer =
BridgeInternal.serializeJsonToByteBuffer(this.clientTelemetryInfo,
ClientTelemetry.OBJECT_MAPPER);
Flux<byte[]> fluxBytes = Flux.just(RxDocumentServiceRequest.toByteArray(byteBuffer));
Map<String, String> headers = new HashMap<>();
String date = Utils.nowAsRFC1123();
headers.put(HttpConstants.HttpHeaders.X_DATE, date);
String authorization = this.tokenProvider.getUserAuthorizationToken(
"", ResourceType.ClientTelemetry, RequestVerb.POST, headers,
AuthorizationTokenType.PrimaryMasterKey, null);
try {
authorization = URLEncoder.encode(authorization, Constants.UrlEncodingInfo.UTF_8);
} catch (UnsupportedEncodingException e) {
logger.error("Failed to encode authToken. Exception: ", e);
this.clearDataForNextRun();
return this.sendClientTelemetry();
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
httpHeaders.set(HttpConstants.HttpHeaders.CONTENT_ENCODING, RuntimeConstants.Encoding.GZIP);
httpHeaders.set(HttpConstants.HttpHeaders.X_DATE, date);
httpHeaders.set(HttpConstants.HttpHeaders.DATABASE_ACCOUNT_NAME,
this.globalDatabaseAccountName);
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
String envName = Configs.getEnvironmentName();
if (StringUtils.isNotEmpty(envName)) {
httpHeaders.set(HttpConstants.HttpHeaders.ENVIRONMENT_NAME, envName);
}
HttpRequest httpRequest = new HttpRequest(HttpMethod.POST, targetEndpoint,
targetEndpoint.getPort(), httpHeaders, fluxBytes);
Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest,
Duration.ofSeconds(Configs.getHttpResponseTimeoutInSeconds()));
return httpResponseMono.flatMap(response -> {
if (response.statusCode() != HttpConstants.StatusCodes.OK) {
logger.error("Client telemetry request did not succeeded, status code {}",
response.statusCode());
}
this.clearDataForNextRun();
return this.sendClientTelemetry();
}).onErrorResume(throwable -> {
logger.error("Error while sending client telemetry request Exception: ", throwable);
this.clearDataForNextRun();
return this.sendClientTelemetry();
});
}
} catch (JsonProcessingException | URISyntaxException ex) {
logger.error("Error while preparing client telemetry. Exception: ", ex);
this.clearDataForNextRun();
return this.sendClientTelemetry();
}
}).onErrorResume(ex -> {
logger.error("sendClientTelemetry() - Unable to send client telemetry" +
". Exception: ", ex);
clearDataForNextRun();
return this.sendClientTelemetry();
}).subscribeOn(scheduler);
}
private void populateAzureVmMetaData(AzureVMMetadata azureVMMetadata) {
this.clientTelemetryInfo.setApplicationRegion(azureVMMetadata.getLocation());
this.clientTelemetryInfo.setVmId(azureVMMetadata.getVmId());
this.clientTelemetryInfo.setHostEnvInfo(azureVMMetadata.getOsType() + "|" + azureVMMetadata.getSku() +
"|" + azureVMMetadata.getVmSize() + "|" + azureVMMetadata.getAzEnvironment());
}
private static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) {
try {
return OBJECT_MAPPER.readValue(itemResponseBodyAsString, itemClassType);
} catch (IOException e) {
throw new IllegalStateException(
"Failed to parse string [" + itemResponseBodyAsString + "] to POJO.", e);
}
}
private void clearDataForNextRun() {
this.clientTelemetryInfo.getSystemInfoMap().clear();
this.clientTelemetryInfo.getOperationInfoMap().clear();
this.clientTelemetryInfo.getCacheRefreshInfoMap().clear();
for (ConcurrentDoubleHistogram histogram : this.clientTelemetryInfo.getSystemInfoMap().values()) {
histogram.reset();
}
}
private void readHistogram() {
ConcurrentDoubleHistogram cpuHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.CPU_MAX,
ClientTelemetry.CPU_PRECISION);
cpuHistogram.setAutoResize(true);
for (double val : CpuMemoryMonitor.getClientTelemetryCpuLatestList()) {
recordValue(cpuHistogram, val);
}
ReportPayload cpuReportPayload = new ReportPayload(CPU_NAME, CPU_UNIT);
clientTelemetryInfo.getSystemInfoMap().put(cpuReportPayload, cpuHistogram);
ConcurrentDoubleHistogram memoryHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.MEMORY_MAX_IN_MB,
ClientTelemetry.MEMORY_PRECISION);
memoryHistogram.setAutoResize(true);
for (double val : CpuMemoryMonitor.getClientTelemetryMemoryLatestList()) {
recordValue(memoryHistogram, val);
}
ReportPayload memoryReportPayload = new ReportPayload(MEMORY_NAME, MEMORY_UNIT);
clientTelemetryInfo.getSystemInfoMap().put(memoryReportPayload, memoryHistogram);
this.clientTelemetryInfo.setTimeStamp(Instant.now().toString());
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getSystemInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getCacheRefreshInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getOperationInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
}
private void fillMetricsInfo(ReportPayload payload, ConcurrentDoubleHistogram histogram) {
DoubleHistogram copyHistogram = histogram.copy();
payload.getMetricInfo().setCount(copyHistogram.getTotalCount());
payload.getMetricInfo().setMax(copyHistogram.getMaxValue());
payload.getMetricInfo().setMin(copyHistogram.getMinValue());
payload.getMetricInfo().setMean(copyHistogram.getMean());
Map<Double, Double> percentile = new HashMap<>();
percentile.put(PERCENTILE_50, copyHistogram.getValueAtPercentile(PERCENTILE_50));
percentile.put(PERCENTILE_90, copyHistogram.getValueAtPercentile(PERCENTILE_90));
percentile.put(PERCENTILE_95, copyHistogram.getValueAtPercentile(PERCENTILE_95));
percentile.put(PERCENTILE_99, copyHistogram.getValueAtPercentile(PERCENTILE_99));
percentile.put(PERCENTILE_999, copyHistogram.getValueAtPercentile(PERCENTILE_999));
payload.getMetricInfo().setPercentiles(percentile);
}
} | class ClientTelemetry {
public final static int ONE_KB_TO_BYTES = 1024;
public final static int REQUEST_LATENCY_MAX_MILLI_SEC = 300000;
public final static int REQUEST_LATENCY_SUCCESS_PRECISION = 4;
public final static int REQUEST_LATENCY_FAILURE_PRECISION = 2;
public final static String REQUEST_LATENCY_NAME = "RequestLatency";
public final static String REQUEST_LATENCY_UNIT = "MilliSecond";
public final static int REQUEST_CHARGE_MAX = 10000;
public final static int REQUEST_CHARGE_PRECISION = 2;
public final static String REQUEST_CHARGE_NAME = "RequestCharge";
public final static String REQUEST_CHARGE_UNIT = "RU";
public final static String TCP_NEW_CHANNEL_LATENCY_NAME = "TcpNewChannelOpenLatency";
public final static String TCP_NEW_CHANNEL_LATENCY_UNIT = "MilliSecond";
public final static int TCP_NEW_CHANNEL_LATENCY_MAX_MILLI_SEC = 300000;
public final static int TCP_NEW_CHANNEL_LATENCY_PRECISION = 2;
public final static int CPU_MAX = 100;
public final static int CPU_PRECISION = 2;
private final static String CPU_NAME = "CPU";
private final static String CPU_UNIT = "Percentage";
public final static int MEMORY_MAX_IN_MB = 102400;
public final static int MEMORY_PRECISION = 2;
private final static String MEMORY_NAME = "MemoryRemaining";
private final static String MEMORY_UNIT = "MB";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final static AtomicLong instanceCount = new AtomicLong(0);
private final static AtomicReference<AzureVMMetadata> azureVmMetaDataSingleton =
new AtomicReference<>(null);
private ClientTelemetryInfo clientTelemetryInfo;
private final HttpClient httpClient;
private final ScheduledThreadPoolExecutor scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
new CosmosDaemonThreadFactory("ClientTelemetry-" + instanceCount.incrementAndGet()));
private final Scheduler scheduler = Schedulers.fromExecutor(scheduledExecutorService);
private static final Logger logger = LoggerFactory.getLogger(ClientTelemetry.class);
private volatile boolean isClosed;
private volatile boolean isClientTelemetryEnabled;
private static String AZURE_VM_METADATA = "http:
private static final double PERCENTILE_50 = 50.0;
private static final double PERCENTILE_90 = 90.0;
private static final double PERCENTILE_95 = 95.0;
private static final double PERCENTILE_99 = 99.0;
private static final double PERCENTILE_999 = 99.9;
private final int clientTelemetrySchedulingSec;
private final IAuthorizationTokenProvider tokenProvider;
private final String globalDatabaseAccountName;
public ClientTelemetry(DiagnosticsClientContext diagnosticsClientContext,
Boolean acceleratedNetworking,
String clientId,
String processId,
String userAgent,
ConnectionMode connectionMode,
String globalDatabaseAccountName,
String applicationRegion,
String hostEnvInfo,
HttpClient httpClient,
boolean isClientTelemetryEnabled,
IAuthorizationTokenProvider tokenProvider,
List<String> preferredRegions
) {
clientTelemetryInfo = new ClientTelemetryInfo(
getMachineId(diagnosticsClientContext),
clientId,
processId,
userAgent,
connectionMode,
globalDatabaseAccountName,
applicationRegion,
hostEnvInfo,
acceleratedNetworking,
preferredRegions);
this.isClosed = false;
this.httpClient = httpClient;
this.isClientTelemetryEnabled = isClientTelemetryEnabled;
this.clientTelemetrySchedulingSec = Configs.getClientTelemetrySchedulingInSec();
this.tokenProvider = tokenProvider;
this.globalDatabaseAccountName = globalDatabaseAccountName;
}
public ClientTelemetryInfo getClientTelemetryInfo() {
return clientTelemetryInfo;
}
public static String getMachineId(DiagnosticsClientContext diagnosticsClientContext) {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null && metadataSnapshot.getVmId() != null) {
String machineId = "vmId:" + metadataSnapshot.getVmId();
if (diagnosticsClientContext != null) {
diagnosticsClientContext.getConfig().withMachineId(machineId);
}
return machineId;
}
if (diagnosticsClientContext == null) {
return "";
}
return diagnosticsClientContext.getConfig().getMachineId();
}
public static void recordValue(ConcurrentDoubleHistogram doubleHistogram, long value) {
try {
doubleHistogram.recordValue(value);
} catch (Exception ex) {
logger.warn("Error while recording value for client telemetry. ", ex);
}
}
public static void recordValue(ConcurrentDoubleHistogram doubleHistogram, double value) {
try {
doubleHistogram.recordValue(value);
} catch (Exception ex) {
logger.warn("Error while recording value for client telemetry. ", ex);
}
}
public boolean isClientTelemetryEnabled() {
return isClientTelemetryEnabled;
}
public void init() {
loadAzureVmMetaData();
sendClientTelemetry().subscribe();
}
public void close() {
this.isClosed = true;
this.scheduledExecutorService.shutdown();
logger.debug("GlobalEndpointManager closed.");
}
private Mono<Void> sendClientTelemetry() {
return Mono.delay(Duration.ofSeconds(clientTelemetrySchedulingSec), CosmosSchedulers.COSMOS_PARALLEL)
.flatMap(t -> {
if (this.isClosed) {
logger.warn("client already closed");
return Mono.empty();
}
if (!Configs.isClientTelemetryEnabled(this.isClientTelemetryEnabled)) {
logger.trace("client telemetry not enabled");
return Mono.empty();
}
readHistogram();
try {
String endpoint = Configs.getClientTelemetryEndpoint();
if (StringUtils.isEmpty(endpoint)) {
logger.info("ClientTelemetry {}",
OBJECT_MAPPER.writeValueAsString(this.clientTelemetryInfo));
clearDataForNextRun();
return this.sendClientTelemetry();
} else {
URI targetEndpoint = new URI(endpoint);
ByteBuffer byteBuffer =
BridgeInternal.serializeJsonToByteBuffer(this.clientTelemetryInfo,
ClientTelemetry.OBJECT_MAPPER);
Flux<byte[]> fluxBytes = Flux.just(RxDocumentServiceRequest.toByteArray(byteBuffer));
Map<String, String> headers = new HashMap<>();
String date = Utils.nowAsRFC1123();
headers.put(HttpConstants.HttpHeaders.X_DATE, date);
String authorization = this.tokenProvider.getUserAuthorizationToken(
"", ResourceType.ClientTelemetry, RequestVerb.POST, headers,
AuthorizationTokenType.PrimaryMasterKey, null);
try {
authorization = URLEncoder.encode(authorization, Constants.UrlEncodingInfo.UTF_8);
} catch (UnsupportedEncodingException e) {
logger.error("Failed to encode authToken. Exception: ", e);
this.clearDataForNextRun();
return this.sendClientTelemetry();
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
httpHeaders.set(HttpConstants.HttpHeaders.CONTENT_ENCODING, RuntimeConstants.Encoding.GZIP);
httpHeaders.set(HttpConstants.HttpHeaders.X_DATE, date);
httpHeaders.set(HttpConstants.HttpHeaders.DATABASE_ACCOUNT_NAME,
this.globalDatabaseAccountName);
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
String envName = Configs.getEnvironmentName();
if (StringUtils.isNotEmpty(envName)) {
httpHeaders.set(HttpConstants.HttpHeaders.ENVIRONMENT_NAME, envName);
}
HttpRequest httpRequest = new HttpRequest(HttpMethod.POST, targetEndpoint,
targetEndpoint.getPort(), httpHeaders, fluxBytes);
Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest,
Duration.ofSeconds(Configs.getHttpResponseTimeoutInSeconds()));
return httpResponseMono.flatMap(response -> {
if (response.statusCode() != HttpConstants.StatusCodes.OK) {
logger.error("Client telemetry request did not succeeded, status code {}",
response.statusCode());
}
this.clearDataForNextRun();
return this.sendClientTelemetry();
}).onErrorResume(throwable -> {
logger.error("Error while sending client telemetry request Exception: ", throwable);
this.clearDataForNextRun();
return this.sendClientTelemetry();
});
}
} catch (JsonProcessingException | URISyntaxException ex) {
logger.error("Error while preparing client telemetry. Exception: ", ex);
this.clearDataForNextRun();
return this.sendClientTelemetry();
}
}).onErrorResume(ex -> {
logger.error("sendClientTelemetry() - Unable to send client telemetry" +
". Exception: ", ex);
clearDataForNextRun();
return this.sendClientTelemetry();
}).subscribeOn(scheduler);
}
private void populateAzureVmMetaData(AzureVMMetadata azureVMMetadata) {
this.clientTelemetryInfo.setApplicationRegion(azureVMMetadata.getLocation());
this.clientTelemetryInfo.setMachineId("vmId:" + azureVMMetadata.getVmId());
this.clientTelemetryInfo.setHostEnvInfo(azureVMMetadata.getOsType() + "|" + azureVMMetadata.getSku() +
"|" + azureVMMetadata.getVmSize() + "|" + azureVMMetadata.getAzEnvironment());
}
private static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) {
try {
return OBJECT_MAPPER.readValue(itemResponseBodyAsString, itemClassType);
} catch (IOException e) {
throw new IllegalStateException(
"Failed to parse string [" + itemResponseBodyAsString + "] to POJO.", e);
}
}
private void clearDataForNextRun() {
this.clientTelemetryInfo.getSystemInfoMap().clear();
this.clientTelemetryInfo.getOperationInfoMap().clear();
this.clientTelemetryInfo.getCacheRefreshInfoMap().clear();
for (ConcurrentDoubleHistogram histogram : this.clientTelemetryInfo.getSystemInfoMap().values()) {
histogram.reset();
}
}
private void readHistogram() {
ConcurrentDoubleHistogram cpuHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.CPU_MAX,
ClientTelemetry.CPU_PRECISION);
cpuHistogram.setAutoResize(true);
for (double val : CpuMemoryMonitor.getClientTelemetryCpuLatestList()) {
recordValue(cpuHistogram, val);
}
ReportPayload cpuReportPayload = new ReportPayload(CPU_NAME, CPU_UNIT);
clientTelemetryInfo.getSystemInfoMap().put(cpuReportPayload, cpuHistogram);
ConcurrentDoubleHistogram memoryHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.MEMORY_MAX_IN_MB,
ClientTelemetry.MEMORY_PRECISION);
memoryHistogram.setAutoResize(true);
for (double val : CpuMemoryMonitor.getClientTelemetryMemoryLatestList()) {
recordValue(memoryHistogram, val);
}
ReportPayload memoryReportPayload = new ReportPayload(MEMORY_NAME, MEMORY_UNIT);
clientTelemetryInfo.getSystemInfoMap().put(memoryReportPayload, memoryHistogram);
this.clientTelemetryInfo.setTimeStamp(Instant.now().toString());
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getSystemInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getCacheRefreshInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getOperationInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
}
private void fillMetricsInfo(ReportPayload payload, ConcurrentDoubleHistogram histogram) {
DoubleHistogram copyHistogram = histogram.copy();
payload.getMetricInfo().setCount(copyHistogram.getTotalCount());
payload.getMetricInfo().setMax(copyHistogram.getMaxValue());
payload.getMetricInfo().setMin(copyHistogram.getMinValue());
payload.getMetricInfo().setMean(copyHistogram.getMean());
Map<Double, Double> percentile = new HashMap<>();
percentile.put(PERCENTILE_50, copyHistogram.getValueAtPercentile(PERCENTILE_50));
percentile.put(PERCENTILE_90, copyHistogram.getValueAtPercentile(PERCENTILE_90));
percentile.put(PERCENTILE_95, copyHistogram.getValueAtPercentile(PERCENTILE_95));
percentile.put(PERCENTILE_99, copyHistogram.getValueAtPercentile(PERCENTILE_99));
percentile.put(PERCENTILE_999, copyHistogram.getValueAtPercentile(PERCENTILE_999));
payload.getMetricInfo().setPercentiles(percentile);
}
} |
It gets initialized per cosmos client instance - while the VM metadata is identical per machine - no need to retrieve it for each new client. | private void loadAzureVmMetaData() {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null) {
this.populateAzureVmMetaData(metadataSnapshot);
return;
}
URI targetEndpoint = null;
try {
targetEndpoint = new URI(AZURE_VM_METADATA);
} catch (URISyntaxException ex) {
logger.info("Unable to parse azure vm metadata url");
return;
}
HashMap<String, String> headers = new HashMap<>();
headers.put("Metadata", "true");
HttpHeaders httpHeaders = new HttpHeaders(headers);
HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(),
httpHeaders);
Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest);
httpResponseMono
.flatMap(response -> response.bodyAsString()).map(metadataJson -> parse(metadataJson,
AzureVMMetadata.class)).doOnSuccess(metadata -> {
azureVmMetaDataSingleton.compareAndSet(null, metadata);
this.populateAzureVmMetaData(metadata);
}).onErrorResume(throwable -> {
logger.info("Client is not on azure vm");
logger.debug("Unable to get azure vm metadata", throwable);
return Mono.empty();
}).subscribe();
} | AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get(); | private void loadAzureVmMetaData() {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null) {
this.populateAzureVmMetaData(metadataSnapshot);
return;
}
URI targetEndpoint = null;
try {
targetEndpoint = new URI(AZURE_VM_METADATA);
} catch (URISyntaxException ex) {
logger.info("Unable to parse azure vm metadata url");
return;
}
HashMap<String, String> headers = new HashMap<>();
headers.put("Metadata", "true");
HttpHeaders httpHeaders = new HttpHeaders(headers);
HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(),
httpHeaders);
Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest);
httpResponseMono
.flatMap(response -> response.bodyAsString()).map(metadataJson -> parse(metadataJson,
AzureVMMetadata.class)).doOnSuccess(metadata -> {
azureVmMetaDataSingleton.compareAndSet(null, metadata);
this.populateAzureVmMetaData(metadata);
}).onErrorResume(throwable -> {
logger.info("Client is not on azure vm");
logger.debug("Unable to get azure vm metadata", throwable);
return Mono.empty();
}).subscribe();
} | class ClientTelemetry {
public final static int ONE_KB_TO_BYTES = 1024;
public final static int REQUEST_LATENCY_MAX_MILLI_SEC = 300000;
public final static int REQUEST_LATENCY_SUCCESS_PRECISION = 4;
public final static int REQUEST_LATENCY_FAILURE_PRECISION = 2;
public final static String REQUEST_LATENCY_NAME = "RequestLatency";
public final static String REQUEST_LATENCY_UNIT = "MilliSecond";
public final static int REQUEST_CHARGE_MAX = 10000;
public final static int REQUEST_CHARGE_PRECISION = 2;
public final static String REQUEST_CHARGE_NAME = "RequestCharge";
public final static String REQUEST_CHARGE_UNIT = "RU";
public final static String TCP_NEW_CHANNEL_LATENCY_NAME = "TcpNewChannelOpenLatency";
public final static String TCP_NEW_CHANNEL_LATENCY_UNIT = "MilliSecond";
public final static int TCP_NEW_CHANNEL_LATENCY_MAX_MILLI_SEC = 300000;
public final static int TCP_NEW_CHANNEL_LATENCY_PRECISION = 2;
public final static int CPU_MAX = 100;
public final static int CPU_PRECISION = 2;
private final static String CPU_NAME = "CPU";
private final static String CPU_UNIT = "Percentage";
public final static int MEMORY_MAX_IN_MB = 102400;
public final static int MEMORY_PRECISION = 2;
private final static String MEMORY_NAME = "MemoryRemaining";
private final static String MEMORY_UNIT = "MB";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final static AtomicLong instanceCount = new AtomicLong(0);
private final static AtomicReference<AzureVMMetadata> azureVmMetaDataSingleton =
new AtomicReference<>(null);
private ClientTelemetryInfo clientTelemetryInfo;
private final HttpClient httpClient;
private final ScheduledThreadPoolExecutor scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
new CosmosDaemonThreadFactory("ClientTelemetry-" + instanceCount.incrementAndGet()));
private final Scheduler scheduler = Schedulers.fromExecutor(scheduledExecutorService);
private static final Logger logger = LoggerFactory.getLogger(ClientTelemetry.class);
private volatile boolean isClosed;
private volatile boolean isClientTelemetryEnabled;
private static String AZURE_VM_METADATA = "http:
private static final double PERCENTILE_50 = 50.0;
private static final double PERCENTILE_90 = 90.0;
private static final double PERCENTILE_95 = 95.0;
private static final double PERCENTILE_99 = 99.0;
private static final double PERCENTILE_999 = 99.9;
private final int clientTelemetrySchedulingSec;
private final IAuthorizationTokenProvider tokenProvider;
private final String globalDatabaseAccountName;
public ClientTelemetry(DiagnosticsClientContext diagnosticsClientContext,
Boolean acceleratedNetworking,
String clientId,
String processId,
String userAgent,
ConnectionMode connectionMode,
String globalDatabaseAccountName,
String applicationRegion,
String hostEnvInfo,
HttpClient httpClient,
boolean isClientTelemetryEnabled,
IAuthorizationTokenProvider tokenProvider,
List<String> preferredRegions
) {
clientTelemetryInfo = new ClientTelemetryInfo(
getMachineId(diagnosticsClientContext),
clientId,
processId,
userAgent,
connectionMode,
globalDatabaseAccountName,
applicationRegion,
hostEnvInfo,
acceleratedNetworking,
preferredRegions);
this.isClosed = false;
this.httpClient = httpClient;
this.isClientTelemetryEnabled = isClientTelemetryEnabled;
this.clientTelemetrySchedulingSec = Configs.getClientTelemetrySchedulingInSec();
this.tokenProvider = tokenProvider;
this.globalDatabaseAccountName = globalDatabaseAccountName;
}
public ClientTelemetryInfo getClientTelemetryInfo() {
return clientTelemetryInfo;
}
public static String getMachineId(DiagnosticsClientContext diagnosticsClientContext) {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null && metadataSnapshot.getVmId() != null) {
String machineId = "vmId:" + metadataSnapshot.getVmId();
if (diagnosticsClientContext != null) {
diagnosticsClientContext.getConfig().withMachineId(machineId);
}
return machineId;
}
if (diagnosticsClientContext == null) {
return "";
}
return diagnosticsClientContext.getConfig().getMachineId();
}
public static void recordValue(ConcurrentDoubleHistogram doubleHistogram, long value) {
try {
doubleHistogram.recordValue(value);
} catch (Exception ex) {
logger.warn("Error while recording value for client telemetry. ", ex);
}
}
public static void recordValue(ConcurrentDoubleHistogram doubleHistogram, double value) {
try {
doubleHistogram.recordValue(value);
} catch (Exception ex) {
logger.warn("Error while recording value for client telemetry. ", ex);
}
}
public boolean isClientTelemetryEnabled() {
return isClientTelemetryEnabled;
}
public void init() {
loadAzureVmMetaData();
sendClientTelemetry().subscribe();
}
public void close() {
this.isClosed = true;
this.scheduledExecutorService.shutdown();
logger.debug("GlobalEndpointManager closed.");
}
private Mono<Void> sendClientTelemetry() {
return Mono.delay(Duration.ofSeconds(clientTelemetrySchedulingSec), CosmosSchedulers.COSMOS_PARALLEL)
.flatMap(t -> {
if (this.isClosed) {
logger.warn("client already closed");
return Mono.empty();
}
if (!Configs.isClientTelemetryEnabled(this.isClientTelemetryEnabled)) {
logger.trace("client telemetry not enabled");
return Mono.empty();
}
readHistogram();
try {
String endpoint = Configs.getClientTelemetryEndpoint();
if (StringUtils.isEmpty(endpoint)) {
logger.info("ClientTelemetry {}",
OBJECT_MAPPER.writeValueAsString(this.clientTelemetryInfo));
clearDataForNextRun();
return this.sendClientTelemetry();
} else {
URI targetEndpoint = new URI(endpoint);
ByteBuffer byteBuffer =
BridgeInternal.serializeJsonToByteBuffer(this.clientTelemetryInfo,
ClientTelemetry.OBJECT_MAPPER);
Flux<byte[]> fluxBytes = Flux.just(RxDocumentServiceRequest.toByteArray(byteBuffer));
Map<String, String> headers = new HashMap<>();
String date = Utils.nowAsRFC1123();
headers.put(HttpConstants.HttpHeaders.X_DATE, date);
String authorization = this.tokenProvider.getUserAuthorizationToken(
"", ResourceType.ClientTelemetry, RequestVerb.POST, headers,
AuthorizationTokenType.PrimaryMasterKey, null);
try {
authorization = URLEncoder.encode(authorization, Constants.UrlEncodingInfo.UTF_8);
} catch (UnsupportedEncodingException e) {
logger.error("Failed to encode authToken. Exception: ", e);
this.clearDataForNextRun();
return this.sendClientTelemetry();
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
httpHeaders.set(HttpConstants.HttpHeaders.CONTENT_ENCODING, RuntimeConstants.Encoding.GZIP);
httpHeaders.set(HttpConstants.HttpHeaders.X_DATE, date);
httpHeaders.set(HttpConstants.HttpHeaders.DATABASE_ACCOUNT_NAME,
this.globalDatabaseAccountName);
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
String envName = Configs.getEnvironmentName();
if (StringUtils.isNotEmpty(envName)) {
httpHeaders.set(HttpConstants.HttpHeaders.ENVIRONMENT_NAME, envName);
}
HttpRequest httpRequest = new HttpRequest(HttpMethod.POST, targetEndpoint,
targetEndpoint.getPort(), httpHeaders, fluxBytes);
Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest,
Duration.ofSeconds(Configs.getHttpResponseTimeoutInSeconds()));
return httpResponseMono.flatMap(response -> {
if (response.statusCode() != HttpConstants.StatusCodes.OK) {
logger.error("Client telemetry request did not succeeded, status code {}",
response.statusCode());
}
this.clearDataForNextRun();
return this.sendClientTelemetry();
}).onErrorResume(throwable -> {
logger.error("Error while sending client telemetry request Exception: ", throwable);
this.clearDataForNextRun();
return this.sendClientTelemetry();
});
}
} catch (JsonProcessingException | URISyntaxException ex) {
logger.error("Error while preparing client telemetry. Exception: ", ex);
this.clearDataForNextRun();
return this.sendClientTelemetry();
}
}).onErrorResume(ex -> {
logger.error("sendClientTelemetry() - Unable to send client telemetry" +
". Exception: ", ex);
clearDataForNextRun();
return this.sendClientTelemetry();
}).subscribeOn(scheduler);
}
private void populateAzureVmMetaData(AzureVMMetadata azureVMMetadata) {
this.clientTelemetryInfo.setApplicationRegion(azureVMMetadata.getLocation());
this.clientTelemetryInfo.setVmId(azureVMMetadata.getVmId());
this.clientTelemetryInfo.setHostEnvInfo(azureVMMetadata.getOsType() + "|" + azureVMMetadata.getSku() +
"|" + azureVMMetadata.getVmSize() + "|" + azureVMMetadata.getAzEnvironment());
}
private static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) {
try {
return OBJECT_MAPPER.readValue(itemResponseBodyAsString, itemClassType);
} catch (IOException e) {
throw new IllegalStateException(
"Failed to parse string [" + itemResponseBodyAsString + "] to POJO.", e);
}
}
private void clearDataForNextRun() {
this.clientTelemetryInfo.getSystemInfoMap().clear();
this.clientTelemetryInfo.getOperationInfoMap().clear();
this.clientTelemetryInfo.getCacheRefreshInfoMap().clear();
for (ConcurrentDoubleHistogram histogram : this.clientTelemetryInfo.getSystemInfoMap().values()) {
histogram.reset();
}
}
private void readHistogram() {
ConcurrentDoubleHistogram cpuHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.CPU_MAX,
ClientTelemetry.CPU_PRECISION);
cpuHistogram.setAutoResize(true);
for (double val : CpuMemoryMonitor.getClientTelemetryCpuLatestList()) {
recordValue(cpuHistogram, val);
}
ReportPayload cpuReportPayload = new ReportPayload(CPU_NAME, CPU_UNIT);
clientTelemetryInfo.getSystemInfoMap().put(cpuReportPayload, cpuHistogram);
ConcurrentDoubleHistogram memoryHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.MEMORY_MAX_IN_MB,
ClientTelemetry.MEMORY_PRECISION);
memoryHistogram.setAutoResize(true);
for (double val : CpuMemoryMonitor.getClientTelemetryMemoryLatestList()) {
recordValue(memoryHistogram, val);
}
ReportPayload memoryReportPayload = new ReportPayload(MEMORY_NAME, MEMORY_UNIT);
clientTelemetryInfo.getSystemInfoMap().put(memoryReportPayload, memoryHistogram);
this.clientTelemetryInfo.setTimeStamp(Instant.now().toString());
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getSystemInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getCacheRefreshInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getOperationInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
}
private void fillMetricsInfo(ReportPayload payload, ConcurrentDoubleHistogram histogram) {
DoubleHistogram copyHistogram = histogram.copy();
payload.getMetricInfo().setCount(copyHistogram.getTotalCount());
payload.getMetricInfo().setMax(copyHistogram.getMaxValue());
payload.getMetricInfo().setMin(copyHistogram.getMinValue());
payload.getMetricInfo().setMean(copyHistogram.getMean());
Map<Double, Double> percentile = new HashMap<>();
percentile.put(PERCENTILE_50, copyHistogram.getValueAtPercentile(PERCENTILE_50));
percentile.put(PERCENTILE_90, copyHistogram.getValueAtPercentile(PERCENTILE_90));
percentile.put(PERCENTILE_95, copyHistogram.getValueAtPercentile(PERCENTILE_95));
percentile.put(PERCENTILE_99, copyHistogram.getValueAtPercentile(PERCENTILE_99));
percentile.put(PERCENTILE_999, copyHistogram.getValueAtPercentile(PERCENTILE_999));
payload.getMetricInfo().setPercentiles(percentile);
}
} | class ClientTelemetry {
public final static int ONE_KB_TO_BYTES = 1024;
public final static int REQUEST_LATENCY_MAX_MILLI_SEC = 300000;
public final static int REQUEST_LATENCY_SUCCESS_PRECISION = 4;
public final static int REQUEST_LATENCY_FAILURE_PRECISION = 2;
public final static String REQUEST_LATENCY_NAME = "RequestLatency";
public final static String REQUEST_LATENCY_UNIT = "MilliSecond";
public final static int REQUEST_CHARGE_MAX = 10000;
public final static int REQUEST_CHARGE_PRECISION = 2;
public final static String REQUEST_CHARGE_NAME = "RequestCharge";
public final static String REQUEST_CHARGE_UNIT = "RU";
public final static String TCP_NEW_CHANNEL_LATENCY_NAME = "TcpNewChannelOpenLatency";
public final static String TCP_NEW_CHANNEL_LATENCY_UNIT = "MilliSecond";
public final static int TCP_NEW_CHANNEL_LATENCY_MAX_MILLI_SEC = 300000;
public final static int TCP_NEW_CHANNEL_LATENCY_PRECISION = 2;
public final static int CPU_MAX = 100;
public final static int CPU_PRECISION = 2;
private final static String CPU_NAME = "CPU";
private final static String CPU_UNIT = "Percentage";
public final static int MEMORY_MAX_IN_MB = 102400;
public final static int MEMORY_PRECISION = 2;
private final static String MEMORY_NAME = "MemoryRemaining";
private final static String MEMORY_UNIT = "MB";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final static AtomicLong instanceCount = new AtomicLong(0);
private final static AtomicReference<AzureVMMetadata> azureVmMetaDataSingleton =
new AtomicReference<>(null);
private ClientTelemetryInfo clientTelemetryInfo;
private final HttpClient httpClient;
private final ScheduledThreadPoolExecutor scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
new CosmosDaemonThreadFactory("ClientTelemetry-" + instanceCount.incrementAndGet()));
private final Scheduler scheduler = Schedulers.fromExecutor(scheduledExecutorService);
private static final Logger logger = LoggerFactory.getLogger(ClientTelemetry.class);
private volatile boolean isClosed;
private volatile boolean isClientTelemetryEnabled;
private static String AZURE_VM_METADATA = "http:
private static final double PERCENTILE_50 = 50.0;
private static final double PERCENTILE_90 = 90.0;
private static final double PERCENTILE_95 = 95.0;
private static final double PERCENTILE_99 = 99.0;
private static final double PERCENTILE_999 = 99.9;
private final int clientTelemetrySchedulingSec;
private final IAuthorizationTokenProvider tokenProvider;
private final String globalDatabaseAccountName;
public ClientTelemetry(DiagnosticsClientContext diagnosticsClientContext,
Boolean acceleratedNetworking,
String clientId,
String processId,
String userAgent,
ConnectionMode connectionMode,
String globalDatabaseAccountName,
String applicationRegion,
String hostEnvInfo,
HttpClient httpClient,
boolean isClientTelemetryEnabled,
IAuthorizationTokenProvider tokenProvider,
List<String> preferredRegions
) {
clientTelemetryInfo = new ClientTelemetryInfo(
getMachineId(diagnosticsClientContext),
clientId,
processId,
userAgent,
connectionMode,
globalDatabaseAccountName,
applicationRegion,
hostEnvInfo,
acceleratedNetworking,
preferredRegions);
this.isClosed = false;
this.httpClient = httpClient;
this.isClientTelemetryEnabled = isClientTelemetryEnabled;
this.clientTelemetrySchedulingSec = Configs.getClientTelemetrySchedulingInSec();
this.tokenProvider = tokenProvider;
this.globalDatabaseAccountName = globalDatabaseAccountName;
}
public ClientTelemetryInfo getClientTelemetryInfo() {
return clientTelemetryInfo;
}
public static String getMachineId(DiagnosticsClientContext diagnosticsClientContext) {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null && metadataSnapshot.getVmId() != null) {
String machineId = "vmId:" + metadataSnapshot.getVmId();
if (diagnosticsClientContext != null) {
diagnosticsClientContext.getConfig().withMachineId(machineId);
}
return machineId;
}
if (diagnosticsClientContext == null) {
return "";
}
return diagnosticsClientContext.getConfig().getMachineId();
}
public static void recordValue(ConcurrentDoubleHistogram doubleHistogram, long value) {
try {
doubleHistogram.recordValue(value);
} catch (Exception ex) {
logger.warn("Error while recording value for client telemetry. ", ex);
}
}
public static void recordValue(ConcurrentDoubleHistogram doubleHistogram, double value) {
try {
doubleHistogram.recordValue(value);
} catch (Exception ex) {
logger.warn("Error while recording value for client telemetry. ", ex);
}
}
public boolean isClientTelemetryEnabled() {
return isClientTelemetryEnabled;
}
public void init() {
loadAzureVmMetaData();
sendClientTelemetry().subscribe();
}
public void close() {
this.isClosed = true;
this.scheduledExecutorService.shutdown();
logger.debug("GlobalEndpointManager closed.");
}
private Mono<Void> sendClientTelemetry() {
return Mono.delay(Duration.ofSeconds(clientTelemetrySchedulingSec), CosmosSchedulers.COSMOS_PARALLEL)
.flatMap(t -> {
if (this.isClosed) {
logger.warn("client already closed");
return Mono.empty();
}
if (!Configs.isClientTelemetryEnabled(this.isClientTelemetryEnabled)) {
logger.trace("client telemetry not enabled");
return Mono.empty();
}
readHistogram();
try {
String endpoint = Configs.getClientTelemetryEndpoint();
if (StringUtils.isEmpty(endpoint)) {
logger.info("ClientTelemetry {}",
OBJECT_MAPPER.writeValueAsString(this.clientTelemetryInfo));
clearDataForNextRun();
return this.sendClientTelemetry();
} else {
URI targetEndpoint = new URI(endpoint);
ByteBuffer byteBuffer =
BridgeInternal.serializeJsonToByteBuffer(this.clientTelemetryInfo,
ClientTelemetry.OBJECT_MAPPER);
Flux<byte[]> fluxBytes = Flux.just(RxDocumentServiceRequest.toByteArray(byteBuffer));
Map<String, String> headers = new HashMap<>();
String date = Utils.nowAsRFC1123();
headers.put(HttpConstants.HttpHeaders.X_DATE, date);
String authorization = this.tokenProvider.getUserAuthorizationToken(
"", ResourceType.ClientTelemetry, RequestVerb.POST, headers,
AuthorizationTokenType.PrimaryMasterKey, null);
try {
authorization = URLEncoder.encode(authorization, Constants.UrlEncodingInfo.UTF_8);
} catch (UnsupportedEncodingException e) {
logger.error("Failed to encode authToken. Exception: ", e);
this.clearDataForNextRun();
return this.sendClientTelemetry();
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
httpHeaders.set(HttpConstants.HttpHeaders.CONTENT_ENCODING, RuntimeConstants.Encoding.GZIP);
httpHeaders.set(HttpConstants.HttpHeaders.X_DATE, date);
httpHeaders.set(HttpConstants.HttpHeaders.DATABASE_ACCOUNT_NAME,
this.globalDatabaseAccountName);
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
String envName = Configs.getEnvironmentName();
if (StringUtils.isNotEmpty(envName)) {
httpHeaders.set(HttpConstants.HttpHeaders.ENVIRONMENT_NAME, envName);
}
HttpRequest httpRequest = new HttpRequest(HttpMethod.POST, targetEndpoint,
targetEndpoint.getPort(), httpHeaders, fluxBytes);
Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest,
Duration.ofSeconds(Configs.getHttpResponseTimeoutInSeconds()));
return httpResponseMono.flatMap(response -> {
if (response.statusCode() != HttpConstants.StatusCodes.OK) {
logger.error("Client telemetry request did not succeeded, status code {}",
response.statusCode());
}
this.clearDataForNextRun();
return this.sendClientTelemetry();
}).onErrorResume(throwable -> {
logger.error("Error while sending client telemetry request Exception: ", throwable);
this.clearDataForNextRun();
return this.sendClientTelemetry();
});
}
} catch (JsonProcessingException | URISyntaxException ex) {
logger.error("Error while preparing client telemetry. Exception: ", ex);
this.clearDataForNextRun();
return this.sendClientTelemetry();
}
}).onErrorResume(ex -> {
logger.error("sendClientTelemetry() - Unable to send client telemetry" +
". Exception: ", ex);
clearDataForNextRun();
return this.sendClientTelemetry();
}).subscribeOn(scheduler);
}
private void populateAzureVmMetaData(AzureVMMetadata azureVMMetadata) {
this.clientTelemetryInfo.setApplicationRegion(azureVMMetadata.getLocation());
this.clientTelemetryInfo.setMachineId("vmId:" + azureVMMetadata.getVmId());
this.clientTelemetryInfo.setHostEnvInfo(azureVMMetadata.getOsType() + "|" + azureVMMetadata.getSku() +
"|" + azureVMMetadata.getVmSize() + "|" + azureVMMetadata.getAzEnvironment());
}
private static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) {
try {
return OBJECT_MAPPER.readValue(itemResponseBodyAsString, itemClassType);
} catch (IOException e) {
throw new IllegalStateException(
"Failed to parse string [" + itemResponseBodyAsString + "] to POJO.", e);
}
}
private void clearDataForNextRun() {
this.clientTelemetryInfo.getSystemInfoMap().clear();
this.clientTelemetryInfo.getOperationInfoMap().clear();
this.clientTelemetryInfo.getCacheRefreshInfoMap().clear();
for (ConcurrentDoubleHistogram histogram : this.clientTelemetryInfo.getSystemInfoMap().values()) {
histogram.reset();
}
}
private void readHistogram() {
ConcurrentDoubleHistogram cpuHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.CPU_MAX,
ClientTelemetry.CPU_PRECISION);
cpuHistogram.setAutoResize(true);
for (double val : CpuMemoryMonitor.getClientTelemetryCpuLatestList()) {
recordValue(cpuHistogram, val);
}
ReportPayload cpuReportPayload = new ReportPayload(CPU_NAME, CPU_UNIT);
clientTelemetryInfo.getSystemInfoMap().put(cpuReportPayload, cpuHistogram);
ConcurrentDoubleHistogram memoryHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.MEMORY_MAX_IN_MB,
ClientTelemetry.MEMORY_PRECISION);
memoryHistogram.setAutoResize(true);
for (double val : CpuMemoryMonitor.getClientTelemetryMemoryLatestList()) {
recordValue(memoryHistogram, val);
}
ReportPayload memoryReportPayload = new ReportPayload(MEMORY_NAME, MEMORY_UNIT);
clientTelemetryInfo.getSystemInfoMap().put(memoryReportPayload, memoryHistogram);
this.clientTelemetryInfo.setTimeStamp(Instant.now().toString());
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getSystemInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getCacheRefreshInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getOperationInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
}
private void fillMetricsInfo(ReportPayload payload, ConcurrentDoubleHistogram histogram) {
DoubleHistogram copyHistogram = histogram.copy();
payload.getMetricInfo().setCount(copyHistogram.getTotalCount());
payload.getMetricInfo().setMax(copyHistogram.getMaxValue());
payload.getMetricInfo().setMin(copyHistogram.getMinValue());
payload.getMetricInfo().setMean(copyHistogram.getMean());
Map<Double, Double> percentile = new HashMap<>();
percentile.put(PERCENTILE_50, copyHistogram.getValueAtPercentile(PERCENTILE_50));
percentile.put(PERCENTILE_90, copyHistogram.getValueAtPercentile(PERCENTILE_90));
percentile.put(PERCENTILE_95, copyHistogram.getValueAtPercentile(PERCENTILE_95));
percentile.put(PERCENTILE_99, copyHistogram.getValueAtPercentile(PERCENTILE_99));
percentile.put(PERCENTILE_999, copyHistogram.getValueAtPercentile(PERCENTILE_999));
payload.getMetricInfo().setPercentiles(percentile);
}
} |
No - UUID id intentional is meant to be stable across cosmos clients - to be bale to use it to see whether errors for example are happening mostly/exclusively form a single client machine. For apps/customer using multiple clients (for example against different accounts) we wouldn't be able to have that correlation right now. | public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) {
try {
this.httpClientInterceptor = httpClientInterceptor;
if (httpClientInterceptor != null) {
this.reactorHttpClient = httpClientInterceptor.apply(httpClient());
}
this.gatewayProxy = createRxGatewayProxy(this.sessionContainer,
this.consistencyLevel,
this.queryCompatibilityMode,
this.userAgentContainer,
this.globalEndpointManager,
this.reactorHttpClient,
this.apiType);
this.globalEndpointManager.init();
this.initializeGatewayConfigurationReader();
if (metadataCachesSnapshot != null) {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy,
metadataCachesSnapshot.getCollectionInfoByNameCache(),
metadataCachesSnapshot.getCollectionInfoByIdCache()
);
} else {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy);
}
this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy);
this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this,
collectionCache);
updateGatewayProxy();
clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(),
ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(),
connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(),
null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions());
clientTelemetry.init();
if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) {
this.storeModel = this.gatewayProxy;
} else {
this.initializeDirectConnectivity();
}
this.retryPolicy.setRxCollectionCache(this.collectionCache);
} catch (Exception e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
} | clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(), | public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) {
try {
this.httpClientInterceptor = httpClientInterceptor;
if (httpClientInterceptor != null) {
this.reactorHttpClient = httpClientInterceptor.apply(httpClient());
}
this.gatewayProxy = createRxGatewayProxy(this.sessionContainer,
this.consistencyLevel,
this.queryCompatibilityMode,
this.userAgentContainer,
this.globalEndpointManager,
this.reactorHttpClient,
this.apiType);
this.globalEndpointManager.init();
this.initializeGatewayConfigurationReader();
if (metadataCachesSnapshot != null) {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy,
metadataCachesSnapshot.getCollectionInfoByNameCache(),
metadataCachesSnapshot.getCollectionInfoByIdCache()
);
} else {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy);
}
this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy);
this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this,
collectionCache);
updateGatewayProxy();
clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(),
ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(),
connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(),
null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions());
clientTelemetry.init();
if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) {
this.storeModel = this.gatewayProxy;
} else {
this.initializeDirectConnectivity();
}
this.retryPolicy.setRxCollectionCache(this.collectionCache);
} catch (Exception e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
} | class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener,
DiagnosticsClientContext {
private static final String tempMachineId = "uuid:" + UUID.randomUUID();
private static final AtomicInteger activeClientsCnt = new AtomicInteger(0);
private static final AtomicInteger clientIdGenerator = new AtomicInteger(0);
private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>(
PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey,
PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false);
private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " +
"ParallelDocumentQueryExecutioncontext, but not used";
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper();
private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer();
private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class);
private final String masterKeyOrResourceToken;
private final URI serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel consistencyLevel;
private final BaseAuthorizationTokenProvider authorizationTokenProvider;
private final UserAgentContainer userAgentContainer;
private final boolean hasAuthKeyResourceToken;
private final Configs configs;
private final boolean connectionSharingAcrossClientsEnabled;
private AzureKeyCredential credential;
private final TokenCredential tokenCredential;
private String[] tokenCredentialScopes;
private SimpleTokenCache tokenCredentialCache;
private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver;
AuthorizationTokenType authorizationTokenType;
private SessionContainer sessionContainer;
private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY;
private RxClientCollectionCache collectionCache;
private RxStoreModel gatewayProxy;
private RxStoreModel storeModel;
private GlobalAddressResolver addressResolver;
private RxPartitionKeyRangeCache partitionKeyRangeCache;
private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap;
private final boolean contentResponseOnWriteEnabled;
private Map<String, PartitionedQueryExecutionInfo> queryPlanCache;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final int clientId;
private ClientTelemetry clientTelemetry;
private ApiType apiType;
private IRetryPolicyFactory resetSessionTokenRetryPolicy;
/**
* Compatibility mode: Allows to specify compatibility mode used by client when
* making query requests. Should be removed when application/sql is no longer
* supported.
*/
private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default;
private final GlobalEndpointManager globalEndpointManager;
private final RetryPolicy retryPolicy;
private HttpClient reactorHttpClient;
private Function<HttpClient, HttpClient> httpClientInterceptor;
private volatile boolean useMultipleWriteLocations;
private StoreClientFactory storeClientFactory;
private GatewayServiceConfigurationReader gatewayConfigurationReader;
private final DiagnosticsClientConfig diagnosticsClientConfig;
private final AtomicBoolean throughputControlEnabled;
private ThroughputControlStore throughputControlStore;
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
private RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
if (permissionFeed != null && permissionFeed.size() > 0) {
this.resourceTokensMap = new HashMap<>();
for (Permission permission : permissionFeed) {
String[] segments = StringUtils.split(permission.getResourceLink(),
Constants.Properties.PATH_SEPARATOR.charAt(0));
if (segments.length <= 0) {
throw new IllegalArgumentException("resourceLink");
}
List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null;
PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false);
if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) {
throw new IllegalArgumentException(permission.getResourceLink());
}
partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName);
if (partitionKeyAndResourceTokenPairs == null) {
partitionKeyAndResourceTokenPairs = new ArrayList<>();
this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs);
}
PartitionKey partitionKey = permission.getResourcePartitionKey();
partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair(
partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty,
permission.getToken()));
logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]",
pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken());
}
if(this.resourceTokensMap.isEmpty()) {
throw new IllegalArgumentException("permissionFeed");
}
String firstToken = permissionFeed.get(0).getToken();
if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) {
this.firstResourceTokenFromPermissionFeed = firstToken;
}
}
}
RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
activeClientsCnt.incrementAndGet();
this.clientId = clientIdGenerator.incrementAndGet();
this.diagnosticsClientConfig = new DiagnosticsClientConfig();
this.diagnosticsClientConfig.withClientId(this.clientId);
this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt);
this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled);
this.diagnosticsClientConfig.withConsistency(consistencyLevel);
this.throughputControlEnabled = new AtomicBoolean(false);
logger.info(
"Initializing DocumentClient [{}] with"
+ " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]",
this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol());
try {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
this.configs = configs;
this.masterKeyOrResourceToken = masterKeyOrResourceToken;
this.serviceEndpoint = serviceEndpoint;
this.credential = credential;
this.tokenCredential = tokenCredential;
this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled;
this.authorizationTokenType = AuthorizationTokenType.Invalid;
if (this.credential != null) {
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.authorizationTokenProvider = null;
hasAuthKeyResourceToken = true;
this.authorizationTokenType = AuthorizationTokenType.ResourceToken;
} else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken);
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else {
hasAuthKeyResourceToken = false;
this.authorizationTokenProvider = null;
if (tokenCredential != null) {
this.tokenCredentialScopes = new String[] {
serviceEndpoint.getScheme() + ":
};
this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential
.getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes)));
this.authorizationTokenType = AuthorizationTokenType.AadToken;
}
}
if (connectionPolicy != null) {
this.connectionPolicy = connectionPolicy;
} else {
this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig());
}
this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode());
this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled());
this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled());
this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions());
this.diagnosticsClientConfig.withMachineId(tempMachineId);
boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled);
this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing);
this.consistencyLevel = consistencyLevel;
this.userAgentContainer = new UserAgentContainer();
String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix();
if (userAgentSuffix != null && userAgentSuffix.length() > 0) {
userAgentContainer.setSuffix(userAgentSuffix);
}
this.httpClientInterceptor = null;
this.reactorHttpClient = httpClient();
this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs);
this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy);
this.resetSessionTokenRetryPolicy = retryPolicy;
CpuMemoryMonitor.register(this);
this.queryPlanCache = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE));
this.apiType = apiType;
} catch (RuntimeException e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
}
@Override
public DiagnosticsClientConfig getConfig() {
return diagnosticsClientConfig;
}
@Override
public CosmosDiagnostics createDiagnostics() {
return BridgeInternal.createCosmosDiagnostics(this, this.globalEndpointManager);
}
private void initializeGatewayConfigurationReader() {
this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager);
DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount();
if (databaseAccount == null) {
logger.error("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
throw new RuntimeException("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
}
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount);
}
private void updateGatewayProxy() {
((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader);
((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache);
((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache);
((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations);
}
public void serialize(CosmosClientMetadataCachesSnapshot state) {
RxCollectionCache.serialize(state, this.collectionCache);
}
private void initializeDirectConnectivity() {
this.addressResolver = new GlobalAddressResolver(this,
this.reactorHttpClient,
this.globalEndpointManager,
this.configs.getProtocol(),
this,
this.collectionCache,
this.partitionKeyRangeCache,
userAgentContainer,
null,
this.connectionPolicy,
this.apiType);
this.storeClientFactory = new StoreClientFactory(
this.addressResolver,
this.diagnosticsClientConfig,
this.configs,
this.connectionPolicy,
this.userAgentContainer,
this.connectionSharingAcrossClientsEnabled,
this.clientTelemetry
);
this.createStoreModel(true);
}
DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() {
return new DatabaseAccountManagerInternal() {
@Override
public URI getServiceEndpoint() {
return RxDocumentClientImpl.this.getServiceEndpoint();
}
@Override
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
logger.info("Getting database account endpoint from {}", endpoint);
return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return RxDocumentClientImpl.this.getConnectionPolicy();
}
};
}
RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer,
ConsistencyLevel consistencyLevel,
QueryCompatibilityMode queryCompatibilityMode,
UserAgentContainer userAgentContainer,
GlobalEndpointManager globalEndpointManager,
HttpClient httpClient,
ApiType apiType) {
return new RxGatewayStoreModel(
this,
sessionContainer,
consistencyLevel,
queryCompatibilityMode,
userAgentContainer,
globalEndpointManager,
httpClient,
apiType);
}
private HttpClient httpClient() {
HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs)
.withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout())
.withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize())
.withProxy(this.connectionPolicy.getProxy())
.withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout());
if (connectionSharingAcrossClientsEnabled) {
return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig);
} else {
diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig);
return HttpClient.createFixed(httpClientConfig);
}
}
private void createStoreModel(boolean subscribeRntbdStatus) {
StoreClient storeClient = this.storeClientFactory.createStoreClient(this,
this.addressResolver,
this.sessionContainer,
this.gatewayConfigurationReader,
this,
this.useMultipleWriteLocations
);
this.storeModel = new ServerStoreModel(storeClient);
}
@Override
public URI getServiceEndpoint() {
return this.serviceEndpoint;
}
@Override
public URI getWriteEndpoint() {
return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null);
}
@Override
public URI getReadEndpoint() {
return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return this.connectionPolicy;
}
@Override
public boolean isContentResponseOnWriteEnabled() {
return contentResponseOnWriteEnabled;
}
@Override
public ConsistencyLevel getConsistencyLevel() {
return consistencyLevel;
}
@Override
public ClientTelemetry getClientTelemetry() {
return this.clientTelemetry;
}
@Override
public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (database == null) {
throw new IllegalArgumentException("Database");
}
logger.debug("Creating a Database. id: [{}]", database.getId());
validateResource(database);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Reading a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT);
}
private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) {
switch (resourceTypeEnum) {
case Database:
return Paths.DATABASES_ROOT;
case DocumentCollection:
return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT);
case Document:
return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT);
case Offer:
return Paths.OFFERS_ROOT;
case User:
return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT);
case ClientEncryptionKey:
return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
case Permission:
return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT);
case Attachment:
return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT);
case StoredProcedure:
return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
case Trigger:
return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT);
case UserDefinedFunction:
return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
case Conflict:
return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT);
default:
throw new IllegalArgumentException("resource type not supported");
}
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) {
if (options == null) {
return null;
}
return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options);
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) {
if (options == null) {
return null;
}
return options.getOperationContextAndListenerTuple();
}
private <T extends Resource> Flux<FeedResponse<T>> createQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum) {
String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum);
UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getCorrelationActivityId(options);
UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ?
correlationActivityIdOfRequestOptions : Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this,
getOperationContextAndListenerTuple(options));
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> createQueryInternal(
resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId),
invalidPartitionExceptionRetryPolicy);
}
private <T extends Resource> Flux<FeedResponse<T>> createQueryInternal(
String resourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
IDocumentQueryClient queryClient,
UUID activityId) {
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory
.createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery,
options, resourceLink, false, activityId,
Configs.isQueryPlanCachingEnabled(), queryPlanCache);
AtomicBoolean isFirstResponse = new AtomicBoolean(true);
return executionContext.flatMap(iDocumentQueryExecutionContext -> {
QueryInfo queryInfo = null;
if (iDocumentQueryExecutionContext instanceof PipelinedDocumentQueryExecutionContext) {
queryInfo = ((PipelinedDocumentQueryExecutionContext<T>) iDocumentQueryExecutionContext).getQueryInfo();
}
QueryInfo finalQueryInfo = queryInfo;
return iDocumentQueryExecutionContext.executeAsync()
.map(tFeedResponse -> {
if (finalQueryInfo != null) {
if (finalQueryInfo.hasSelectValue()) {
ModelBridgeInternal
.addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo);
}
if (isFirstResponse.compareAndSet(true, false)) {
ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse,
finalQueryInfo.getQueryPlanDiagnosticsContext());
}
}
return tFeedResponse;
});
});
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) {
return queryDatabases(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database);
}
@Override
public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink,
DocumentCollection collection, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink,
DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink,
collection.getId());
validateResource(collection);
String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
});
} catch (Exception e) {
logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Replacing a Collection. id: [{}]", collection.getId());
validateResource(collection);
String path = Utils.joinPath(collection.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
if (resourceResponse.getResource() != null) {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
}
});
} catch (Exception e) {
logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.DELETE)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated));
}
private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated ->
this.getStoreProxy(requestPopulated).processMessage(requestPopulated)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
));
}
@Override
public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class,
Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection);
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection);
}
private static String serializeProcedureParams(List<Object> objectArray) {
String[] stringArray = new String[objectArray.size()];
for (int i = 0; i < objectArray.size(); ++i) {
Object object = objectArray.get(i);
if (object instanceof JsonSerializable) {
stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object);
} else {
try {
stringArray[i] = mapper.writeValueAsString(object);
} catch (IOException e) {
throw new IllegalArgumentException("Can't serialize the object into the json string", e);
}
}
}
return String.format("[%s]", StringUtils.join(stringArray, ","));
}
private static void validateResource(Resource resource) {
if (!StringUtils.isEmpty(resource.getId())) {
if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 ||
resource.getId().indexOf('?') != -1 || resource.getId().indexOf('
throw new IllegalArgumentException("Id contains illegal chars.");
}
if (resource.getId().endsWith(" ")) {
throw new IllegalArgumentException("Id ends with a space.");
}
}
}
private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) {
Map<String, String> headers = new HashMap<>();
if (this.useMultipleWriteLocations) {
headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString());
}
if (consistencyLevel != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString());
}
if (options == null) {
if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
return headers;
}
Map<String, String> customOptions = options.getHeaders();
if (customOptions != null) {
headers.putAll(customOptions);
}
boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled;
if (options.isContentResponseOnWriteEnabled() != null) {
contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled();
}
if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
if (options.getIfMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag());
}
if(options.getIfNoneMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag());
}
if (options.getConsistencyLevel() != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString());
}
if (options.getIndexingDirective() != null) {
headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString());
}
if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) {
String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude);
}
if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) {
String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude);
}
if (!Strings.isNullOrEmpty(options.getSessionToken())) {
headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken());
}
if (options.getResourceTokenExpirySeconds() != null) {
headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY,
String.valueOf(options.getResourceTokenExpirySeconds()));
}
if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString());
} else if (options.getOfferType() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType());
}
if (options.getOfferThroughput() == null) {
if (options.getThroughputProperties() != null) {
Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties());
final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings();
OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null;
if (offerAutoscaleSettings != null) {
autoscaleAutoUpgradeProperties
= offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties();
}
if (offer.hasOfferThroughput() &&
(offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 ||
autoscaleAutoUpgradeProperties != null &&
autoscaleAutoUpgradeProperties
.getAutoscaleThroughputProperties()
.getIncrementPercent() >= 0)) {
throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with "
+ "fixed offer");
}
if (offer.hasOfferThroughput()) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput()));
} else if (offer.getOfferAutoScaleSettings() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS,
ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings()));
}
}
}
if (options.isQuotaInfoEnabled()) {
headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true));
}
if (options.isScriptLoggingEnabled()) {
headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true));
}
if (options.getDedicatedGatewayRequestOptions() != null &&
options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) {
headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS,
String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions())));
}
return headers;
}
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return this.resetSessionTokenRetryPolicy;
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Document document,
RequestOptions options) {
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs
.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object document,
RequestOptions options,
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) {
return collectionObs.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private void addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object objectDoc, RequestOptions options,
DocumentCollection collection) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
PartitionKeyInternal partitionKeyInternal = null;
if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else if (options != null && options.getPartitionKey() != null) {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey());
} else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) {
partitionKeyInternal = PartitionKeyInternal.getEmpty();
} else if (contentAsByteBuffer != null || objectDoc != null) {
InternalObjectNode internalObjectNode;
if (objectDoc instanceof InternalObjectNode) {
internalObjectNode = (InternalObjectNode) objectDoc;
} else if (objectDoc instanceof ObjectNode) {
internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc);
} else if (contentAsByteBuffer != null) {
contentAsByteBuffer.rewind();
internalObjectNode = new InternalObjectNode(contentAsByteBuffer);
} else {
throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null");
}
Instant serializationStartTime = Instant.now();
partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTime,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION
);
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
} else {
throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation.");
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
}
public static PartitionKeyInternal extractPartitionKeyValueFromDocument(
InternalObjectNode document,
PartitionKeyDefinition partitionKeyDefinition) {
if (partitionKeyDefinition != null) {
switch (partitionKeyDefinition.getKind()) {
case HASH:
String path = partitionKeyDefinition.getPaths().iterator().next();
List<String> parts = PathParser.getPathParts(path);
if (parts.size() >= 1) {
Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts);
if (value == null || value.getClass() == ObjectNode.class) {
value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
}
if (value instanceof PartitionKeyInternal) {
return (PartitionKeyInternal) value;
} else {
return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false);
}
}
break;
case MULTI_HASH:
Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()];
for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){
String partitionPath = partitionKeyDefinition.getPaths().get(pathIter);
List<String> partitionPathParts = PathParser.getPathParts(partitionPath);
partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts);
}
return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false);
default:
throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind());
}
}
return null;
}
private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
Object document,
RequestOptions options,
boolean disableAutomaticIdGeneration,
OperationType operationType) {
if (StringUtils.isEmpty(documentCollectionLink)) {
throw new IllegalArgumentException("documentCollectionLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Document, path, requestHeaders, options, content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return addPartitionKeyInformation(request, content, document, options, collectionObs);
}
private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink");
checkNotNull(serverBatchRequest, "expected non null serverBatchRequest");
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody()));
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Batch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> {
addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v);
return request;
});
}
private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request,
ServerBatchRequest serverBatchRequest,
DocumentCollection collection) {
if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) {
PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue();
PartitionKeyInternal partitionKeyInternal;
if (partitionKey.equals(PartitionKey.NONE)) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey);
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
} else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) {
request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId()));
} else {
throw new UnsupportedOperationException("Unknown Server request.");
}
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString());
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch()));
request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError()));
request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size());
return request;
}
private Mono<RxDocumentServiceRequest> populateHeaders(RxDocumentServiceRequest request, RequestVerb httpMethod) {
request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123());
if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null
|| this.cosmosAuthorizationTokenResolver != null || this.credential != null) {
String resourceName = request.getResourceAddress();
String authorization = this.getUserAuthorizationToken(
resourceName, request.getResourceType(), httpMethod, request.getHeaders(),
AuthorizationTokenType.PrimaryMasterKey, request.properties);
try {
authorization = URLEncoder.encode(authorization, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Failed to encode authtoken.", e);
}
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
}
if (this.apiType != null) {
request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString());
}
if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod))
&& !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
}
if (RequestVerb.PATCH.equals(httpMethod) &&
!request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH);
}
if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) {
request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
}
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
if (this.requiresFeedRangeFiltering(request)) {
return request.getFeedRange()
.populateFeedRangeFilteringHeaders(
this.getPartitionKeyRangeCache(),
request,
this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request))
.flatMap(this::populateAuthorizationHeader);
}
return this.populateAuthorizationHeader(request);
}
private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) {
if (request.getResourceType() != ResourceType.Document &&
request.getResourceType() != ResourceType.Conflict) {
return false;
}
switch (request.getOperationType()) {
case ReadFeed:
case Query:
case SqlQuery:
return request.getFeedRange() != null;
default:
return false;
}
}
@Override
public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) {
if (request == null) {
throw new IllegalArgumentException("request");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return request;
});
} else {
return Mono.just(request);
}
}
@Override
public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) {
if (httpHeaders == null) {
throw new IllegalArgumentException("httpHeaders");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return httpHeaders;
});
}
return Mono.just(httpHeaders);
}
@Override
public AuthorizationTokenType getAuthorizationTokenType() {
return this.authorizationTokenType;
}
@Override
public String getUserAuthorizationToken(String resourceName,
ResourceType resourceType,
RequestVerb requestVerb,
Map<String, String> headers,
AuthorizationTokenType tokenType,
Map<String, Object> properties) {
if (this.cosmosAuthorizationTokenResolver != null) {
return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(),
properties != null ? Collections.unmodifiableMap(properties) : null);
} else if (credential != null) {
return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName,
resourceType, headers);
} else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) {
return masterKeyOrResourceToken;
} else {
assert resourceTokensMap != null;
if(resourceType.equals(ResourceType.DatabaseAccount)) {
return this.firstResourceTokenFromPermissionFeed;
}
return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers);
}
}
private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) {
CosmosResourceType cosmosResourceType =
ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString());
if (cosmosResourceType == null) {
return CosmosResourceType.SYSTEM;
}
return cosmosResourceType;
}
void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) {
this.sessionContainer.setSessionToken(request, response.getResponseHeaders());
}
private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
Map<String, String> headers = requestPopulated.getHeaders();
assert (headers != null);
headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true");
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
);
});
}
private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.PUT)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PATCH);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(request).processMessage(request);
}
@Override
public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) {
try {
logger.debug("Creating a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Create);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance);
}
private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Upsert);
Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = Utils.getCollectionName(documentLink);
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Document typedDocument = documentFromObject(document, mapper);
return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = document.getSelfLink();
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (document == null) {
throw new IllegalArgumentException("document");
}
return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a database due to [{}]", e.getMessage());
return Mono.error(e);
}
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink,
Document document,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
if (document == null) {
throw new IllegalArgumentException("document");
}
logger.debug("Replacing a Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = serializeJsonToByteBuffer(document);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs);
return requestObs.flatMap(req -> replace(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> patchDocument(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink");
checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations");
logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options));
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Patch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(
request,
null,
null,
options,
collectionObs);
return requestObs.flatMap(req -> patch(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy);
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Deleting a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs);
return requestObs.flatMap(req -> this
.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> this
.deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting documents due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Reading a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> {
return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Document>> readDocuments(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return queryDocuments(collectionLink, "SELECT * FROM r", options);
}
@Override
public <T> Mono<FeedResponse<T>> readMany(
List<CosmosItemIdentity> itemIdentityList,
String collectionLink,
CosmosQueryRequestOptions options,
Class<T> klass) {
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink, null
);
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request);
return collectionObs
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache
.tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null);
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap =
new HashMap<>();
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
itemIdentityList
.forEach(itemIdentity -> {
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(
itemIdentity.getPartitionKey()),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
if (partitionRangeItemKeyMap.get(range) == null) {
List<CosmosItemIdentity> list = new ArrayList<>();
list.add(itemIdentity);
partitionRangeItemKeyMap.put(range, list);
} else {
List<CosmosItemIdentity> pairs =
partitionRangeItemKeyMap.get(range);
pairs.add(itemIdentity);
partitionRangeItemKeyMap.put(range, pairs);
}
});
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap;
rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap,
collection.getPartitionKey());
return createReadManyQuery(
resourceLink,
new SqlQuerySpec(DUMMY_SQL_QUERY),
options,
Document.class,
ResourceType.Document,
collection,
Collections.unmodifiableMap(rangeQueryMap))
.collectList()
.map(feedList -> {
List<T> finalList = new ArrayList<>();
HashMap<String, String> headers = new HashMap<>();
ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>();
double requestCharge = 0;
for (FeedResponse<Document> page : feedList) {
ConcurrentMap<String, QueryMetrics> pageQueryMetrics =
ModelBridgeInternal.queryMetrics(page);
if (pageQueryMetrics != null) {
pageQueryMetrics.forEach(
aggregatedQueryMetrics::putIfAbsent);
}
requestCharge += page.getRequestCharge();
finalList.addAll(page.getResults().stream().map(document ->
ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList()));
}
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double
.toString(requestCharge));
FeedResponse<T> frp = BridgeInternal
.createFeedResponse(finalList, headers);
return frp;
});
});
}
);
}
private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap(
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap,
PartitionKeyDefinition partitionKeyDefinition) {
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>();
String partitionKeySelector = createPkSelector(partitionKeyDefinition);
for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) {
SqlQuerySpec sqlQuerySpec;
if (partitionKeySelector.equals("[\"id\"]")) {
sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector);
} else {
sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector);
}
rangeQueryMap.put(entry.getKey(), sqlQuerySpec);
}
return rangeQueryMap;
}
private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(
List<CosmosItemIdentity> idPartitionKeyPairList,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( ");
for (int i = 0; i < idPartitionKeyPairList.size(); i++) {
CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i);
String idValue = itemIdentity.getId();
String idParamName = "@param" + i;
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
if (!Objects.equals(idValue, pkValue)) {
continue;
}
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append(idParamName);
if (i < idPartitionKeyPairList.size() - 1) {
queryStringBuilder.append(", ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE ( ");
for (int i = 0; i < itemIdentities.size(); i++) {
CosmosItemIdentity itemIdentity = itemIdentities.get(i);
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
String pkParamName = "@param" + (2 * i);
parameters.add(new SqlParameter(pkParamName, pkValue));
String idValue = itemIdentity.getId();
String idParamName = "@param" + (2 * i + 1);
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append("(");
queryStringBuilder.append("c.id = ");
queryStringBuilder.append(idParamName);
queryStringBuilder.append(" AND ");
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
queryStringBuilder.append(" )");
if (i < itemIdentities.size() - 1) {
queryStringBuilder.append(" OR ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) {
return partitionKeyDefinition.getPaths()
.stream()
.map(pathPart -> StringUtils.substring(pathPart, 1))
.map(pathPart -> StringUtils.replace(pathPart, "\"", "\\"))
.map(part -> "[\"" + part + "\"]")
.collect(Collectors.joining());
}
private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
DocumentCollection collection,
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) {
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(),
sqlQuery,
rangeQueryMap,
options,
collection.getResourceId(),
parentResourceLink,
activityId,
klass,
resourceTypeEnum);
return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync);
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, String query, CosmosQueryRequestOptions options) {
return queryDocuments(collectionLink, new SqlQuerySpec(query), options);
}
private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return new IDocumentQueryClient () {
@Override
public RxCollectionCache getCollectionCache() {
return RxDocumentClientImpl.this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return RxDocumentClientImpl.this.partitionKeyRangeCache;
}
@Override
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy;
}
@Override
public ConsistencyLevel getDefaultConsistencyLevelAsync() {
return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel();
}
@Override
public ConsistencyLevel getDesiredConsistencyLevelAsync() {
return RxDocumentClientImpl.this.consistencyLevel;
}
@Override
public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) {
if (operationContextAndListenerTuple == null) {
return RxDocumentClientImpl.this.query(request).single();
} else {
final OperationListener listener =
operationContextAndListenerTuple.getOperationListener();
final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext();
request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId());
listener.requestListener(operationContext, request);
return RxDocumentClientImpl.this.query(request).single().doOnNext(
response -> listener.responseListener(operationContext, response)
).doOnError(
ex -> listener.exceptionListener(operationContext, ex)
);
}
}
@Override
public QueryCompatibilityMode getQueryCompatibilityMode() {
return QueryCompatibilityMode.Default;
}
@Override
public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) {
return null;
}
};
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
SqlQuerySpecLogger.getInstance().logQuery(querySpec);
return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document);
}
@Override
public Flux<FeedResponse<Document>> queryDocumentChangeFeed(
final DocumentCollection collection,
final CosmosChangeFeedRequestOptions changeFeedOptions) {
checkNotNull(collection, "Argument 'collection' must not be null.");
ChangeFeedQueryImpl<Document> changeFeedQueryImpl = new ChangeFeedQueryImpl<>(
this,
ResourceType.Document,
Document.class,
collection.getAltLink(),
collection.getResourceId(),
changeFeedOptions);
return changeFeedQueryImpl.executeAsync();
}
@Override
public Flux<FeedResponse<Document>> readAllDocuments(
String collectionLink,
PartitionKey partitionKey,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (partitionKey == null) {
throw new IllegalArgumentException("partitionKey");
}
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null
);
Flux<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request).flux();
return collectionObs.flatMap(documentCollectionResourceResponse -> {
DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
String pkSelector = createPkSelector(pkDefinition);
SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector);
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
final CosmosQueryRequestOptions effectiveOptions =
ModelBridgeInternal.createQueryRequestOptions(options);
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> {
Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache
.tryLookupAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null).flux();
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(partitionKey),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
return createQueryInternal(
resourceLink,
querySpec,
ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()),
Document.class,
ResourceType.Document,
queryClient,
activityId);
});
},
invalidPartitionExceptionRetryPolicy);
});
}
@Override
public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() {
return queryPlanCache;
}
@Override
public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class,
Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT));
}
private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
validateResource(storedProcedure);
String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType,
ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
return request;
}
private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (udf == null) {
throw new IllegalArgumentException("udf");
}
validateResource(udf);
String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Create);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId());
RxDocumentClientImpl.validateResource(storedProcedure);
String path = Utils.joinPath(storedProcedure.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class,
Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
List<Object> procedureParams) {
return this.executeStoredProcedure(storedProcedureLink, null, procedureParams);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy);
}
@Override
public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy);
}
private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) {
try {
logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript);
requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ExecuteJavaScript,
ResourceType.StoredProcedure, path,
procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "",
requestHeaders, options);
if (retryPolicy != null) {
retryPolicy.onBeforeSendRequest(request);
}
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options))
.map(response -> {
this.captureSessionToken(request, response);
return toStoredProcedureResponse(response);
}));
} catch (Exception e) {
logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
DocumentClientRetryPolicy requestRetryPolicy,
boolean disableAutomaticIdGeneration) {
try {
logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size());
Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true));
} catch (Exception ex) {
logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex);
return Mono.error(ex);
}
}
@Override
public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path,
trigger, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId());
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(trigger.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Trigger, Trigger.class,
Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryTriggers(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger);
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (udf == null) {
throw new IllegalArgumentException("udf");
}
logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId());
validateResource(udf);
String path = Utils.joinPath(udf.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class,
Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
String query, CosmosQueryRequestOptions options) {
return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction);
}
@Override
public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Conflict, Conflict.class,
Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryConflicts(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict);
}
@Override
public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (user == null) {
throw new IllegalArgumentException("user");
}
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.User, path, user, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (user == null) {
throw new IllegalArgumentException("user");
}
logger.debug("Replacing a User. user id [{}]", user.getId());
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(user.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.User, path, user, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Deleting a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Reading a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.User, User.class,
Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) {
return queryUsers(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User);
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(clientEncryptionKeyLink)) {
throw new IllegalArgumentException("clientEncryptionKeyLink");
}
logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink);
String path = Utils.joinPath(clientEncryptionKeyLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink,
ClientEncryptionKey clientEncryptionKey, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId());
RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey,
String nameBasedLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey,
nameBasedLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId());
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(nameBasedLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey,
OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders,
options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class,
Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey);
}
@Override
public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy());
}
private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
if (permission == null) {
throw new IllegalArgumentException("permission");
}
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Permission, path, permission, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (permission == null) {
throw new IllegalArgumentException("permission");
}
logger.debug("Replacing a Permission. permission id [{}]", permission.getId());
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(permission.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Reading a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
return readFeed(options, ResourceType.Permission, Permission.class,
Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query,
CosmosQueryRequestOptions options) {
return queryPermissions(userLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission);
}
@Override
public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
if (offer == null) {
throw new IllegalArgumentException("offer");
}
logger.debug("Replacing an Offer. offer id [{}]", offer.getId());
RxDocumentClientImpl.validateResource(offer);
String path = Utils.joinPath(offer.getSelfLink(), null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace,
ResourceType.Offer, path, offer, null, null);
return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Offer>> readOffer(String offerLink) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(offerLink)) {
throw new IllegalArgumentException("offerLink");
}
logger.debug("Reading an Offer. offerLink [{}]", offerLink);
String path = Utils.joinPath(offerLink, null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Offer, Offer.class,
Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null));
}
private <T extends Resource> Flux<FeedResponse<T>> readFeed(CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options);
int maxPageSize = maxItemCount != null ? maxItemCount : -1;
final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options;
DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> {
Map<String, String> requestHeaders = new HashMap<>();
if (continuationToken != null) {
requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken);
}
requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize));
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions);
retryPolicy.onBeforeSendRequest(request);
return request;
};
Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper
.inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)),
retryPolicy);
return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, maxPageSize);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) {
return queryOffers(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer);
}
@Override
public Mono<DatabaseAccount> getDatabaseAccount() {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy),
documentClientRetryPolicy);
}
@Override
public DatabaseAccount getLatestDatabaseAccount() {
return this.globalEndpointManager.getLatestDatabaseAccount();
}
private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Getting Database Account");
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read,
ResourceType.DatabaseAccount, "",
(HashMap<String, String>) null,
null);
return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount);
} catch (Exception e) {
logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Object getSession() {
return this.sessionContainer;
}
public void setSession(Object sessionContainer) {
this.sessionContainer = (SessionContainer) sessionContainer;
}
@Override
public RxClientCollectionCache getCollectionCache() {
return this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return partitionKeyRangeCache;
}
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
return Flux.defer(() -> {
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null);
return this.populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
requestPopulated.setEndpointOverride(endpoint);
return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> {
String message = String.format("Failed to retrieve database account information. %s",
e.getCause() != null
? e.getCause().toString()
: e.toString());
logger.warn(message);
}).map(rsp -> rsp.getResource(DatabaseAccount.class))
.doOnNext(databaseAccount ->
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled()
&& BridgeInternal.isEnableMultipleWriteLocations(databaseAccount));
});
});
}
/**
* Certain requests must be routed through gateway even when the client connectivity mode is direct.
*
* @param request
* @return RxStoreModel
*/
private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) {
if (request.UseGatewayMode) {
return this.gatewayProxy;
}
ResourceType resourceType = request.getResourceType();
OperationType operationType = request.getOperationType();
if (resourceType == ResourceType.Offer ||
resourceType == ResourceType.ClientEncryptionKey ||
resourceType.isScript() && operationType != OperationType.ExecuteJavaScript ||
resourceType == ResourceType.PartitionKeyRange ||
resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) {
return this.gatewayProxy;
}
if (operationType == OperationType.Create
|| operationType == OperationType.Upsert) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection ||
resourceType == ResourceType.Permission) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Delete) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Replace) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Read) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else {
if ((operationType == OperationType.Query ||
operationType == OperationType.SqlQuery ||
operationType == OperationType.ReadFeed) &&
Utils.isCollectionChild(request.getResourceType())) {
if (request.getPartitionKeyRangeIdentity() == null &&
request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) {
return this.gatewayProxy;
}
}
return this.storeModel;
}
}
@Override
public void close() {
logger.info("Attempting to close client {}", this.clientId);
if (!closed.getAndSet(true)) {
this.activeClientsCnt.decrementAndGet();
logger.info("Shutting down ...");
logger.info("Closing Global Endpoint Manager ...");
LifeCycleUtils.closeQuietly(this.globalEndpointManager);
logger.info("Closing StoreClientFactory ...");
LifeCycleUtils.closeQuietly(this.storeClientFactory);
logger.info("Shutting down reactorHttpClient ...");
LifeCycleUtils.closeQuietly(this.reactorHttpClient);
logger.info("Shutting down CpuMonitor ...");
CpuMemoryMonitor.unregister(this);
if (this.throughputControlEnabled.get()) {
logger.info("Closing ThroughputControlStore ...");
this.throughputControlStore.close();
}
logger.info("Shutting down completed.");
} else {
logger.warn("Already shutdown!");
}
}
@Override
public ItemDeserializer getItemDeserializer() {
return this.itemDeserializer;
}
@Override
public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group can not be null");
if (this.throughputControlEnabled.compareAndSet(false, true)) {
this.throughputControlStore =
new ThroughputControlStore(
this.collectionCache,
this.connectionPolicy.getConnectionMode(),
this.partitionKeyRangeCache);
this.storeModel.enableThroughputControl(throughputControlStore);
}
this.throughputControlStore.enableThroughputControlGroup(group);
}
private static SqlQuerySpec createLogicalPartitionScanQuerySpec(
PartitionKey partitionKey,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE");
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey);
String pkParamName = "@pkValue";
parameters.add(new SqlParameter(pkParamName, pkValue));
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
@Override
public Mono<List<FeedRange>> getFeedRanges(String collectionLink) {
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
collectionLink,
new HashMap<>());
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null);
invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request);
return ObservableHelper.inlineIfPossibleAsObs(
() -> getFeedRangesInternal(request, collectionLink),
invalidPartitionExceptionRetryPolicy);
}
private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) {
logger.debug("getFeedRange collectionLink=[{}]", collectionLink);
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null,
request);
return collectionObs.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache
.tryGetOverlappingRangesAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null);
return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request));
});
}
private static List<FeedRange> toFeedRanges(
Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) {
final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v;
if (partitionKeyRangeList == null) {
request.forceNameCacheRefresh = true;
throw new InvalidPartitionException();
}
List<FeedRange> feedRanges = new ArrayList<>();
partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange)));
return feedRanges;
}
private static FeedRange toFeedRange(PartitionKeyRange pkRange) {
return new FeedRangeEpkImpl(pkRange.toRange());
}
} | class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener,
DiagnosticsClientContext {
private static final String tempMachineId = "uuid:" + UUID.randomUUID();
private static final AtomicInteger activeClientsCnt = new AtomicInteger(0);
private static final AtomicInteger clientIdGenerator = new AtomicInteger(0);
private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>(
PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey,
PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false);
private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " +
"ParallelDocumentQueryExecutioncontext, but not used";
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper();
private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer();
private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class);
private final String masterKeyOrResourceToken;
private final URI serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel consistencyLevel;
private final BaseAuthorizationTokenProvider authorizationTokenProvider;
private final UserAgentContainer userAgentContainer;
private final boolean hasAuthKeyResourceToken;
private final Configs configs;
private final boolean connectionSharingAcrossClientsEnabled;
private AzureKeyCredential credential;
private final TokenCredential tokenCredential;
private String[] tokenCredentialScopes;
private SimpleTokenCache tokenCredentialCache;
private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver;
AuthorizationTokenType authorizationTokenType;
private SessionContainer sessionContainer;
private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY;
private RxClientCollectionCache collectionCache;
private RxStoreModel gatewayProxy;
private RxStoreModel storeModel;
private GlobalAddressResolver addressResolver;
private RxPartitionKeyRangeCache partitionKeyRangeCache;
private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap;
private final boolean contentResponseOnWriteEnabled;
private Map<String, PartitionedQueryExecutionInfo> queryPlanCache;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final int clientId;
private ClientTelemetry clientTelemetry;
private ApiType apiType;
private IRetryPolicyFactory resetSessionTokenRetryPolicy;
/**
* Compatibility mode: Allows to specify compatibility mode used by client when
* making query requests. Should be removed when application/sql is no longer
* supported.
*/
private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default;
private final GlobalEndpointManager globalEndpointManager;
private final RetryPolicy retryPolicy;
private HttpClient reactorHttpClient;
private Function<HttpClient, HttpClient> httpClientInterceptor;
private volatile boolean useMultipleWriteLocations;
private StoreClientFactory storeClientFactory;
private GatewayServiceConfigurationReader gatewayConfigurationReader;
private final DiagnosticsClientConfig diagnosticsClientConfig;
private final AtomicBoolean throughputControlEnabled;
private ThroughputControlStore throughputControlStore;
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
private RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
if (permissionFeed != null && permissionFeed.size() > 0) {
this.resourceTokensMap = new HashMap<>();
for (Permission permission : permissionFeed) {
String[] segments = StringUtils.split(permission.getResourceLink(),
Constants.Properties.PATH_SEPARATOR.charAt(0));
if (segments.length <= 0) {
throw new IllegalArgumentException("resourceLink");
}
List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null;
PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false);
if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) {
throw new IllegalArgumentException(permission.getResourceLink());
}
partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName);
if (partitionKeyAndResourceTokenPairs == null) {
partitionKeyAndResourceTokenPairs = new ArrayList<>();
this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs);
}
PartitionKey partitionKey = permission.getResourcePartitionKey();
partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair(
partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty,
permission.getToken()));
logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]",
pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken());
}
if(this.resourceTokensMap.isEmpty()) {
throw new IllegalArgumentException("permissionFeed");
}
String firstToken = permissionFeed.get(0).getToken();
if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) {
this.firstResourceTokenFromPermissionFeed = firstToken;
}
}
}
RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
activeClientsCnt.incrementAndGet();
this.clientId = clientIdGenerator.incrementAndGet();
this.diagnosticsClientConfig = new DiagnosticsClientConfig();
this.diagnosticsClientConfig.withClientId(this.clientId);
this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt);
this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled);
this.diagnosticsClientConfig.withConsistency(consistencyLevel);
this.throughputControlEnabled = new AtomicBoolean(false);
logger.info(
"Initializing DocumentClient [{}] with"
+ " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]",
this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol());
try {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
this.configs = configs;
this.masterKeyOrResourceToken = masterKeyOrResourceToken;
this.serviceEndpoint = serviceEndpoint;
this.credential = credential;
this.tokenCredential = tokenCredential;
this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled;
this.authorizationTokenType = AuthorizationTokenType.Invalid;
if (this.credential != null) {
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.authorizationTokenProvider = null;
hasAuthKeyResourceToken = true;
this.authorizationTokenType = AuthorizationTokenType.ResourceToken;
} else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken);
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else {
hasAuthKeyResourceToken = false;
this.authorizationTokenProvider = null;
if (tokenCredential != null) {
this.tokenCredentialScopes = new String[] {
serviceEndpoint.getScheme() + ":
};
this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential
.getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes)));
this.authorizationTokenType = AuthorizationTokenType.AadToken;
}
}
if (connectionPolicy != null) {
this.connectionPolicy = connectionPolicy;
} else {
this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig());
}
this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode());
this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled());
this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled());
this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions());
this.diagnosticsClientConfig.withMachineId(tempMachineId);
boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled);
this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing);
this.consistencyLevel = consistencyLevel;
this.userAgentContainer = new UserAgentContainer();
String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix();
if (userAgentSuffix != null && userAgentSuffix.length() > 0) {
userAgentContainer.setSuffix(userAgentSuffix);
}
this.httpClientInterceptor = null;
this.reactorHttpClient = httpClient();
this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs);
this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy);
this.resetSessionTokenRetryPolicy = retryPolicy;
CpuMemoryMonitor.register(this);
this.queryPlanCache = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE));
this.apiType = apiType;
} catch (RuntimeException e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
}
@Override
public DiagnosticsClientConfig getConfig() {
return diagnosticsClientConfig;
}
@Override
public CosmosDiagnostics createDiagnostics() {
return BridgeInternal.createCosmosDiagnostics(this, this.globalEndpointManager);
}
private void initializeGatewayConfigurationReader() {
this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager);
DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount();
if (databaseAccount == null) {
logger.error("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
throw new RuntimeException("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
}
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount);
}
private void updateGatewayProxy() {
((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader);
((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache);
((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache);
((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations);
}
public void serialize(CosmosClientMetadataCachesSnapshot state) {
RxCollectionCache.serialize(state, this.collectionCache);
}
private void initializeDirectConnectivity() {
this.addressResolver = new GlobalAddressResolver(this,
this.reactorHttpClient,
this.globalEndpointManager,
this.configs.getProtocol(),
this,
this.collectionCache,
this.partitionKeyRangeCache,
userAgentContainer,
null,
this.connectionPolicy,
this.apiType);
this.storeClientFactory = new StoreClientFactory(
this.addressResolver,
this.diagnosticsClientConfig,
this.configs,
this.connectionPolicy,
this.userAgentContainer,
this.connectionSharingAcrossClientsEnabled,
this.clientTelemetry
);
this.createStoreModel(true);
}
DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() {
return new DatabaseAccountManagerInternal() {
@Override
public URI getServiceEndpoint() {
return RxDocumentClientImpl.this.getServiceEndpoint();
}
@Override
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
logger.info("Getting database account endpoint from {}", endpoint);
return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return RxDocumentClientImpl.this.getConnectionPolicy();
}
};
}
RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer,
ConsistencyLevel consistencyLevel,
QueryCompatibilityMode queryCompatibilityMode,
UserAgentContainer userAgentContainer,
GlobalEndpointManager globalEndpointManager,
HttpClient httpClient,
ApiType apiType) {
return new RxGatewayStoreModel(
this,
sessionContainer,
consistencyLevel,
queryCompatibilityMode,
userAgentContainer,
globalEndpointManager,
httpClient,
apiType);
}
private HttpClient httpClient() {
HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs)
.withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout())
.withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize())
.withProxy(this.connectionPolicy.getProxy())
.withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout());
if (connectionSharingAcrossClientsEnabled) {
return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig);
} else {
diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig);
return HttpClient.createFixed(httpClientConfig);
}
}
private void createStoreModel(boolean subscribeRntbdStatus) {
StoreClient storeClient = this.storeClientFactory.createStoreClient(this,
this.addressResolver,
this.sessionContainer,
this.gatewayConfigurationReader,
this,
this.useMultipleWriteLocations
);
this.storeModel = new ServerStoreModel(storeClient);
}
@Override
public URI getServiceEndpoint() {
return this.serviceEndpoint;
}
@Override
public URI getWriteEndpoint() {
return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null);
}
@Override
public URI getReadEndpoint() {
return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return this.connectionPolicy;
}
@Override
public boolean isContentResponseOnWriteEnabled() {
return contentResponseOnWriteEnabled;
}
@Override
public ConsistencyLevel getConsistencyLevel() {
return consistencyLevel;
}
@Override
public ClientTelemetry getClientTelemetry() {
return this.clientTelemetry;
}
@Override
public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (database == null) {
throw new IllegalArgumentException("Database");
}
logger.debug("Creating a Database. id: [{}]", database.getId());
validateResource(database);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Reading a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT);
}
private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) {
switch (resourceTypeEnum) {
case Database:
return Paths.DATABASES_ROOT;
case DocumentCollection:
return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT);
case Document:
return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT);
case Offer:
return Paths.OFFERS_ROOT;
case User:
return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT);
case ClientEncryptionKey:
return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
case Permission:
return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT);
case Attachment:
return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT);
case StoredProcedure:
return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
case Trigger:
return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT);
case UserDefinedFunction:
return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
case Conflict:
return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT);
default:
throw new IllegalArgumentException("resource type not supported");
}
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) {
if (options == null) {
return null;
}
return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options);
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) {
if (options == null) {
return null;
}
return options.getOperationContextAndListenerTuple();
}
private <T extends Resource> Flux<FeedResponse<T>> createQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum) {
String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum);
UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getCorrelationActivityId(options);
UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ?
correlationActivityIdOfRequestOptions : Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this,
getOperationContextAndListenerTuple(options));
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> createQueryInternal(
resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId),
invalidPartitionExceptionRetryPolicy);
}
private <T extends Resource> Flux<FeedResponse<T>> createQueryInternal(
String resourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
IDocumentQueryClient queryClient,
UUID activityId) {
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory
.createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery,
options, resourceLink, false, activityId,
Configs.isQueryPlanCachingEnabled(), queryPlanCache);
AtomicBoolean isFirstResponse = new AtomicBoolean(true);
return executionContext.flatMap(iDocumentQueryExecutionContext -> {
QueryInfo queryInfo = null;
if (iDocumentQueryExecutionContext instanceof PipelinedDocumentQueryExecutionContext) {
queryInfo = ((PipelinedDocumentQueryExecutionContext<T>) iDocumentQueryExecutionContext).getQueryInfo();
}
QueryInfo finalQueryInfo = queryInfo;
return iDocumentQueryExecutionContext.executeAsync()
.map(tFeedResponse -> {
if (finalQueryInfo != null) {
if (finalQueryInfo.hasSelectValue()) {
ModelBridgeInternal
.addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo);
}
if (isFirstResponse.compareAndSet(true, false)) {
ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse,
finalQueryInfo.getQueryPlanDiagnosticsContext());
}
}
return tFeedResponse;
});
});
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) {
return queryDatabases(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database);
}
@Override
public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink,
DocumentCollection collection, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink,
DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink,
collection.getId());
validateResource(collection);
String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
});
} catch (Exception e) {
logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Replacing a Collection. id: [{}]", collection.getId());
validateResource(collection);
String path = Utils.joinPath(collection.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
if (resourceResponse.getResource() != null) {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
}
});
} catch (Exception e) {
logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.DELETE)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated));
}
private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated ->
this.getStoreProxy(requestPopulated).processMessage(requestPopulated)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
));
}
@Override
public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class,
Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection);
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection);
}
private static String serializeProcedureParams(List<Object> objectArray) {
String[] stringArray = new String[objectArray.size()];
for (int i = 0; i < objectArray.size(); ++i) {
Object object = objectArray.get(i);
if (object instanceof JsonSerializable) {
stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object);
} else {
try {
stringArray[i] = mapper.writeValueAsString(object);
} catch (IOException e) {
throw new IllegalArgumentException("Can't serialize the object into the json string", e);
}
}
}
return String.format("[%s]", StringUtils.join(stringArray, ","));
}
private static void validateResource(Resource resource) {
if (!StringUtils.isEmpty(resource.getId())) {
if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 ||
resource.getId().indexOf('?') != -1 || resource.getId().indexOf('
throw new IllegalArgumentException("Id contains illegal chars.");
}
if (resource.getId().endsWith(" ")) {
throw new IllegalArgumentException("Id ends with a space.");
}
}
}
private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) {
Map<String, String> headers = new HashMap<>();
if (this.useMultipleWriteLocations) {
headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString());
}
if (consistencyLevel != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString());
}
if (options == null) {
if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
return headers;
}
Map<String, String> customOptions = options.getHeaders();
if (customOptions != null) {
headers.putAll(customOptions);
}
boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled;
if (options.isContentResponseOnWriteEnabled() != null) {
contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled();
}
if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
if (options.getIfMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag());
}
if(options.getIfNoneMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag());
}
if (options.getConsistencyLevel() != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString());
}
if (options.getIndexingDirective() != null) {
headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString());
}
if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) {
String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude);
}
if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) {
String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude);
}
if (!Strings.isNullOrEmpty(options.getSessionToken())) {
headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken());
}
if (options.getResourceTokenExpirySeconds() != null) {
headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY,
String.valueOf(options.getResourceTokenExpirySeconds()));
}
if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString());
} else if (options.getOfferType() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType());
}
if (options.getOfferThroughput() == null) {
if (options.getThroughputProperties() != null) {
Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties());
final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings();
OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null;
if (offerAutoscaleSettings != null) {
autoscaleAutoUpgradeProperties
= offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties();
}
if (offer.hasOfferThroughput() &&
(offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 ||
autoscaleAutoUpgradeProperties != null &&
autoscaleAutoUpgradeProperties
.getAutoscaleThroughputProperties()
.getIncrementPercent() >= 0)) {
throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with "
+ "fixed offer");
}
if (offer.hasOfferThroughput()) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput()));
} else if (offer.getOfferAutoScaleSettings() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS,
ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings()));
}
}
}
if (options.isQuotaInfoEnabled()) {
headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true));
}
if (options.isScriptLoggingEnabled()) {
headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true));
}
if (options.getDedicatedGatewayRequestOptions() != null &&
options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) {
headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS,
String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions())));
}
return headers;
}
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return this.resetSessionTokenRetryPolicy;
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Document document,
RequestOptions options) {
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs
.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object document,
RequestOptions options,
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) {
return collectionObs.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private void addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object objectDoc, RequestOptions options,
DocumentCollection collection) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
PartitionKeyInternal partitionKeyInternal = null;
if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else if (options != null && options.getPartitionKey() != null) {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey());
} else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) {
partitionKeyInternal = PartitionKeyInternal.getEmpty();
} else if (contentAsByteBuffer != null || objectDoc != null) {
InternalObjectNode internalObjectNode;
if (objectDoc instanceof InternalObjectNode) {
internalObjectNode = (InternalObjectNode) objectDoc;
} else if (objectDoc instanceof ObjectNode) {
internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc);
} else if (contentAsByteBuffer != null) {
contentAsByteBuffer.rewind();
internalObjectNode = new InternalObjectNode(contentAsByteBuffer);
} else {
throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null");
}
Instant serializationStartTime = Instant.now();
partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTime,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION
);
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
} else {
throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation.");
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
}
public static PartitionKeyInternal extractPartitionKeyValueFromDocument(
InternalObjectNode document,
PartitionKeyDefinition partitionKeyDefinition) {
if (partitionKeyDefinition != null) {
switch (partitionKeyDefinition.getKind()) {
case HASH:
String path = partitionKeyDefinition.getPaths().iterator().next();
List<String> parts = PathParser.getPathParts(path);
if (parts.size() >= 1) {
Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts);
if (value == null || value.getClass() == ObjectNode.class) {
value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
}
if (value instanceof PartitionKeyInternal) {
return (PartitionKeyInternal) value;
} else {
return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false);
}
}
break;
case MULTI_HASH:
Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()];
for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){
String partitionPath = partitionKeyDefinition.getPaths().get(pathIter);
List<String> partitionPathParts = PathParser.getPathParts(partitionPath);
partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts);
}
return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false);
default:
throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind());
}
}
return null;
}
private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
Object document,
RequestOptions options,
boolean disableAutomaticIdGeneration,
OperationType operationType) {
if (StringUtils.isEmpty(documentCollectionLink)) {
throw new IllegalArgumentException("documentCollectionLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Document, path, requestHeaders, options, content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return addPartitionKeyInformation(request, content, document, options, collectionObs);
}
private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink");
checkNotNull(serverBatchRequest, "expected non null serverBatchRequest");
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody()));
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Batch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> {
addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v);
return request;
});
}
private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request,
ServerBatchRequest serverBatchRequest,
DocumentCollection collection) {
if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) {
PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue();
PartitionKeyInternal partitionKeyInternal;
if (partitionKey.equals(PartitionKey.NONE)) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey);
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
} else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) {
request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId()));
} else {
throw new UnsupportedOperationException("Unknown Server request.");
}
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString());
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch()));
request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError()));
request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size());
return request;
}
private Mono<RxDocumentServiceRequest> populateHeaders(RxDocumentServiceRequest request, RequestVerb httpMethod) {
request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123());
if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null
|| this.cosmosAuthorizationTokenResolver != null || this.credential != null) {
String resourceName = request.getResourceAddress();
String authorization = this.getUserAuthorizationToken(
resourceName, request.getResourceType(), httpMethod, request.getHeaders(),
AuthorizationTokenType.PrimaryMasterKey, request.properties);
try {
authorization = URLEncoder.encode(authorization, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Failed to encode authtoken.", e);
}
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
}
if (this.apiType != null) {
request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString());
}
if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod))
&& !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
}
if (RequestVerb.PATCH.equals(httpMethod) &&
!request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH);
}
if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) {
request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
}
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
if (this.requiresFeedRangeFiltering(request)) {
return request.getFeedRange()
.populateFeedRangeFilteringHeaders(
this.getPartitionKeyRangeCache(),
request,
this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request))
.flatMap(this::populateAuthorizationHeader);
}
return this.populateAuthorizationHeader(request);
}
private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) {
if (request.getResourceType() != ResourceType.Document &&
request.getResourceType() != ResourceType.Conflict) {
return false;
}
switch (request.getOperationType()) {
case ReadFeed:
case Query:
case SqlQuery:
return request.getFeedRange() != null;
default:
return false;
}
}
@Override
public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) {
if (request == null) {
throw new IllegalArgumentException("request");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return request;
});
} else {
return Mono.just(request);
}
}
@Override
public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) {
if (httpHeaders == null) {
throw new IllegalArgumentException("httpHeaders");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return httpHeaders;
});
}
return Mono.just(httpHeaders);
}
@Override
public AuthorizationTokenType getAuthorizationTokenType() {
return this.authorizationTokenType;
}
@Override
public String getUserAuthorizationToken(String resourceName,
ResourceType resourceType,
RequestVerb requestVerb,
Map<String, String> headers,
AuthorizationTokenType tokenType,
Map<String, Object> properties) {
if (this.cosmosAuthorizationTokenResolver != null) {
return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(),
properties != null ? Collections.unmodifiableMap(properties) : null);
} else if (credential != null) {
return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName,
resourceType, headers);
} else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) {
return masterKeyOrResourceToken;
} else {
assert resourceTokensMap != null;
if(resourceType.equals(ResourceType.DatabaseAccount)) {
return this.firstResourceTokenFromPermissionFeed;
}
return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers);
}
}
private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) {
CosmosResourceType cosmosResourceType =
ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString());
if (cosmosResourceType == null) {
return CosmosResourceType.SYSTEM;
}
return cosmosResourceType;
}
void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) {
this.sessionContainer.setSessionToken(request, response.getResponseHeaders());
}
private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
Map<String, String> headers = requestPopulated.getHeaders();
assert (headers != null);
headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true");
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
);
});
}
private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.PUT)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PATCH);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(request).processMessage(request);
}
@Override
public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) {
try {
logger.debug("Creating a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Create);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance);
}
private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Upsert);
Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = Utils.getCollectionName(documentLink);
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Document typedDocument = documentFromObject(document, mapper);
return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = document.getSelfLink();
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (document == null) {
throw new IllegalArgumentException("document");
}
return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a database due to [{}]", e.getMessage());
return Mono.error(e);
}
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink,
Document document,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
if (document == null) {
throw new IllegalArgumentException("document");
}
logger.debug("Replacing a Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = serializeJsonToByteBuffer(document);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs);
return requestObs.flatMap(req -> replace(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> patchDocument(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink");
checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations");
logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options));
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Patch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(
request,
null,
null,
options,
collectionObs);
return requestObs.flatMap(req -> patch(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy);
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Deleting a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs);
return requestObs.flatMap(req -> this
.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> this
.deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting documents due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Reading a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> {
return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Document>> readDocuments(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return queryDocuments(collectionLink, "SELECT * FROM r", options);
}
@Override
public <T> Mono<FeedResponse<T>> readMany(
List<CosmosItemIdentity> itemIdentityList,
String collectionLink,
CosmosQueryRequestOptions options,
Class<T> klass) {
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink, null
);
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request);
return collectionObs
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache
.tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null);
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap =
new HashMap<>();
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
itemIdentityList
.forEach(itemIdentity -> {
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(
itemIdentity.getPartitionKey()),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
if (partitionRangeItemKeyMap.get(range) == null) {
List<CosmosItemIdentity> list = new ArrayList<>();
list.add(itemIdentity);
partitionRangeItemKeyMap.put(range, list);
} else {
List<CosmosItemIdentity> pairs =
partitionRangeItemKeyMap.get(range);
pairs.add(itemIdentity);
partitionRangeItemKeyMap.put(range, pairs);
}
});
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap;
rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap,
collection.getPartitionKey());
return createReadManyQuery(
resourceLink,
new SqlQuerySpec(DUMMY_SQL_QUERY),
options,
Document.class,
ResourceType.Document,
collection,
Collections.unmodifiableMap(rangeQueryMap))
.collectList()
.map(feedList -> {
List<T> finalList = new ArrayList<>();
HashMap<String, String> headers = new HashMap<>();
ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>();
double requestCharge = 0;
for (FeedResponse<Document> page : feedList) {
ConcurrentMap<String, QueryMetrics> pageQueryMetrics =
ModelBridgeInternal.queryMetrics(page);
if (pageQueryMetrics != null) {
pageQueryMetrics.forEach(
aggregatedQueryMetrics::putIfAbsent);
}
requestCharge += page.getRequestCharge();
finalList.addAll(page.getResults().stream().map(document ->
ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList()));
}
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double
.toString(requestCharge));
FeedResponse<T> frp = BridgeInternal
.createFeedResponse(finalList, headers);
return frp;
});
});
}
);
}
private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap(
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap,
PartitionKeyDefinition partitionKeyDefinition) {
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>();
String partitionKeySelector = createPkSelector(partitionKeyDefinition);
for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) {
SqlQuerySpec sqlQuerySpec;
if (partitionKeySelector.equals("[\"id\"]")) {
sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector);
} else {
sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector);
}
rangeQueryMap.put(entry.getKey(), sqlQuerySpec);
}
return rangeQueryMap;
}
private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(
List<CosmosItemIdentity> idPartitionKeyPairList,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( ");
for (int i = 0; i < idPartitionKeyPairList.size(); i++) {
CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i);
String idValue = itemIdentity.getId();
String idParamName = "@param" + i;
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
if (!Objects.equals(idValue, pkValue)) {
continue;
}
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append(idParamName);
if (i < idPartitionKeyPairList.size() - 1) {
queryStringBuilder.append(", ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE ( ");
for (int i = 0; i < itemIdentities.size(); i++) {
CosmosItemIdentity itemIdentity = itemIdentities.get(i);
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
String pkParamName = "@param" + (2 * i);
parameters.add(new SqlParameter(pkParamName, pkValue));
String idValue = itemIdentity.getId();
String idParamName = "@param" + (2 * i + 1);
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append("(");
queryStringBuilder.append("c.id = ");
queryStringBuilder.append(idParamName);
queryStringBuilder.append(" AND ");
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
queryStringBuilder.append(" )");
if (i < itemIdentities.size() - 1) {
queryStringBuilder.append(" OR ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) {
return partitionKeyDefinition.getPaths()
.stream()
.map(pathPart -> StringUtils.substring(pathPart, 1))
.map(pathPart -> StringUtils.replace(pathPart, "\"", "\\"))
.map(part -> "[\"" + part + "\"]")
.collect(Collectors.joining());
}
private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
DocumentCollection collection,
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) {
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(),
sqlQuery,
rangeQueryMap,
options,
collection.getResourceId(),
parentResourceLink,
activityId,
klass,
resourceTypeEnum);
return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync);
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, String query, CosmosQueryRequestOptions options) {
return queryDocuments(collectionLink, new SqlQuerySpec(query), options);
}
private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return new IDocumentQueryClient () {
@Override
public RxCollectionCache getCollectionCache() {
return RxDocumentClientImpl.this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return RxDocumentClientImpl.this.partitionKeyRangeCache;
}
@Override
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy;
}
@Override
public ConsistencyLevel getDefaultConsistencyLevelAsync() {
return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel();
}
@Override
public ConsistencyLevel getDesiredConsistencyLevelAsync() {
return RxDocumentClientImpl.this.consistencyLevel;
}
@Override
public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) {
if (operationContextAndListenerTuple == null) {
return RxDocumentClientImpl.this.query(request).single();
} else {
final OperationListener listener =
operationContextAndListenerTuple.getOperationListener();
final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext();
request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId());
listener.requestListener(operationContext, request);
return RxDocumentClientImpl.this.query(request).single().doOnNext(
response -> listener.responseListener(operationContext, response)
).doOnError(
ex -> listener.exceptionListener(operationContext, ex)
);
}
}
@Override
public QueryCompatibilityMode getQueryCompatibilityMode() {
return QueryCompatibilityMode.Default;
}
@Override
public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) {
return null;
}
};
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
SqlQuerySpecLogger.getInstance().logQuery(querySpec);
return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document);
}
@Override
public Flux<FeedResponse<Document>> queryDocumentChangeFeed(
final DocumentCollection collection,
final CosmosChangeFeedRequestOptions changeFeedOptions) {
checkNotNull(collection, "Argument 'collection' must not be null.");
ChangeFeedQueryImpl<Document> changeFeedQueryImpl = new ChangeFeedQueryImpl<>(
this,
ResourceType.Document,
Document.class,
collection.getAltLink(),
collection.getResourceId(),
changeFeedOptions);
return changeFeedQueryImpl.executeAsync();
}
@Override
public Flux<FeedResponse<Document>> readAllDocuments(
String collectionLink,
PartitionKey partitionKey,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (partitionKey == null) {
throw new IllegalArgumentException("partitionKey");
}
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null
);
Flux<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request).flux();
return collectionObs.flatMap(documentCollectionResourceResponse -> {
DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
String pkSelector = createPkSelector(pkDefinition);
SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector);
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
final CosmosQueryRequestOptions effectiveOptions =
ModelBridgeInternal.createQueryRequestOptions(options);
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> {
Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache
.tryLookupAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null).flux();
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(partitionKey),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
return createQueryInternal(
resourceLink,
querySpec,
ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()),
Document.class,
ResourceType.Document,
queryClient,
activityId);
});
},
invalidPartitionExceptionRetryPolicy);
});
}
@Override
public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() {
return queryPlanCache;
}
@Override
public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class,
Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT));
}
private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
validateResource(storedProcedure);
String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType,
ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
return request;
}
private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (udf == null) {
throw new IllegalArgumentException("udf");
}
validateResource(udf);
String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Create);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId());
RxDocumentClientImpl.validateResource(storedProcedure);
String path = Utils.joinPath(storedProcedure.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class,
Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
List<Object> procedureParams) {
return this.executeStoredProcedure(storedProcedureLink, null, procedureParams);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy);
}
@Override
public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy);
}
private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) {
try {
logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript);
requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ExecuteJavaScript,
ResourceType.StoredProcedure, path,
procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "",
requestHeaders, options);
if (retryPolicy != null) {
retryPolicy.onBeforeSendRequest(request);
}
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options))
.map(response -> {
this.captureSessionToken(request, response);
return toStoredProcedureResponse(response);
}));
} catch (Exception e) {
logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
DocumentClientRetryPolicy requestRetryPolicy,
boolean disableAutomaticIdGeneration) {
try {
logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size());
Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true));
} catch (Exception ex) {
logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex);
return Mono.error(ex);
}
}
@Override
public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path,
trigger, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId());
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(trigger.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Trigger, Trigger.class,
Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryTriggers(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger);
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (udf == null) {
throw new IllegalArgumentException("udf");
}
logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId());
validateResource(udf);
String path = Utils.joinPath(udf.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class,
Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
String query, CosmosQueryRequestOptions options) {
return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction);
}
@Override
public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Conflict, Conflict.class,
Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryConflicts(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict);
}
@Override
public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (user == null) {
throw new IllegalArgumentException("user");
}
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.User, path, user, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (user == null) {
throw new IllegalArgumentException("user");
}
logger.debug("Replacing a User. user id [{}]", user.getId());
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(user.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.User, path, user, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Deleting a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Reading a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.User, User.class,
Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) {
return queryUsers(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User);
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(clientEncryptionKeyLink)) {
throw new IllegalArgumentException("clientEncryptionKeyLink");
}
logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink);
String path = Utils.joinPath(clientEncryptionKeyLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink,
ClientEncryptionKey clientEncryptionKey, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId());
RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey,
String nameBasedLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey,
nameBasedLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId());
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(nameBasedLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey,
OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders,
options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class,
Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey);
}
@Override
public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy());
}
private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
if (permission == null) {
throw new IllegalArgumentException("permission");
}
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Permission, path, permission, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (permission == null) {
throw new IllegalArgumentException("permission");
}
logger.debug("Replacing a Permission. permission id [{}]", permission.getId());
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(permission.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Reading a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
return readFeed(options, ResourceType.Permission, Permission.class,
Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query,
CosmosQueryRequestOptions options) {
return queryPermissions(userLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission);
}
@Override
public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
if (offer == null) {
throw new IllegalArgumentException("offer");
}
logger.debug("Replacing an Offer. offer id [{}]", offer.getId());
RxDocumentClientImpl.validateResource(offer);
String path = Utils.joinPath(offer.getSelfLink(), null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace,
ResourceType.Offer, path, offer, null, null);
return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Offer>> readOffer(String offerLink) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(offerLink)) {
throw new IllegalArgumentException("offerLink");
}
logger.debug("Reading an Offer. offerLink [{}]", offerLink);
String path = Utils.joinPath(offerLink, null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Offer, Offer.class,
Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null));
}
private <T extends Resource> Flux<FeedResponse<T>> readFeed(CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options);
int maxPageSize = maxItemCount != null ? maxItemCount : -1;
final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options;
DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> {
Map<String, String> requestHeaders = new HashMap<>();
if (continuationToken != null) {
requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken);
}
requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize));
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions);
retryPolicy.onBeforeSendRequest(request);
return request;
};
Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper
.inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)),
retryPolicy);
return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, maxPageSize);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) {
return queryOffers(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer);
}
@Override
public Mono<DatabaseAccount> getDatabaseAccount() {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy),
documentClientRetryPolicy);
}
@Override
public DatabaseAccount getLatestDatabaseAccount() {
return this.globalEndpointManager.getLatestDatabaseAccount();
}
private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Getting Database Account");
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read,
ResourceType.DatabaseAccount, "",
(HashMap<String, String>) null,
null);
return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount);
} catch (Exception e) {
logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Object getSession() {
return this.sessionContainer;
}
public void setSession(Object sessionContainer) {
this.sessionContainer = (SessionContainer) sessionContainer;
}
@Override
public RxClientCollectionCache getCollectionCache() {
return this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return partitionKeyRangeCache;
}
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
return Flux.defer(() -> {
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null);
return this.populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
requestPopulated.setEndpointOverride(endpoint);
return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> {
String message = String.format("Failed to retrieve database account information. %s",
e.getCause() != null
? e.getCause().toString()
: e.toString());
logger.warn(message);
}).map(rsp -> rsp.getResource(DatabaseAccount.class))
.doOnNext(databaseAccount ->
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled()
&& BridgeInternal.isEnableMultipleWriteLocations(databaseAccount));
});
});
}
/**
* Certain requests must be routed through gateway even when the client connectivity mode is direct.
*
* @param request
* @return RxStoreModel
*/
private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) {
if (request.UseGatewayMode) {
return this.gatewayProxy;
}
ResourceType resourceType = request.getResourceType();
OperationType operationType = request.getOperationType();
if (resourceType == ResourceType.Offer ||
resourceType == ResourceType.ClientEncryptionKey ||
resourceType.isScript() && operationType != OperationType.ExecuteJavaScript ||
resourceType == ResourceType.PartitionKeyRange ||
resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) {
return this.gatewayProxy;
}
if (operationType == OperationType.Create
|| operationType == OperationType.Upsert) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection ||
resourceType == ResourceType.Permission) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Delete) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Replace) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Read) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else {
if ((operationType == OperationType.Query ||
operationType == OperationType.SqlQuery ||
operationType == OperationType.ReadFeed) &&
Utils.isCollectionChild(request.getResourceType())) {
if (request.getPartitionKeyRangeIdentity() == null &&
request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) {
return this.gatewayProxy;
}
}
return this.storeModel;
}
}
@Override
public void close() {
logger.info("Attempting to close client {}", this.clientId);
if (!closed.getAndSet(true)) {
activeClientsCnt.decrementAndGet();
logger.info("Shutting down ...");
logger.info("Closing Global Endpoint Manager ...");
LifeCycleUtils.closeQuietly(this.globalEndpointManager);
logger.info("Closing StoreClientFactory ...");
LifeCycleUtils.closeQuietly(this.storeClientFactory);
logger.info("Shutting down reactorHttpClient ...");
LifeCycleUtils.closeQuietly(this.reactorHttpClient);
logger.info("Shutting down CpuMonitor ...");
CpuMemoryMonitor.unregister(this);
if (this.throughputControlEnabled.get()) {
logger.info("Closing ThroughputControlStore ...");
this.throughputControlStore.close();
}
logger.info("Shutting down completed.");
} else {
logger.warn("Already shutdown!");
}
}
@Override
public ItemDeserializer getItemDeserializer() {
return this.itemDeserializer;
}
@Override
public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group can not be null");
if (this.throughputControlEnabled.compareAndSet(false, true)) {
this.throughputControlStore =
new ThroughputControlStore(
this.collectionCache,
this.connectionPolicy.getConnectionMode(),
this.partitionKeyRangeCache);
this.storeModel.enableThroughputControl(throughputControlStore);
}
this.throughputControlStore.enableThroughputControlGroup(group);
}
private static SqlQuerySpec createLogicalPartitionScanQuerySpec(
PartitionKey partitionKey,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE");
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey);
String pkParamName = "@pkValue";
parameters.add(new SqlParameter(pkParamName, pkValue));
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
@Override
public Mono<List<FeedRange>> getFeedRanges(String collectionLink) {
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
collectionLink,
new HashMap<>());
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null);
invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request);
return ObservableHelper.inlineIfPossibleAsObs(
() -> getFeedRangesInternal(request, collectionLink),
invalidPartitionExceptionRetryPolicy);
}
private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) {
logger.debug("getFeedRange collectionLink=[{}]", collectionLink);
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null,
request);
return collectionObs.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache
.tryGetOverlappingRangesAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null);
return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request));
});
}
private static List<FeedRange> toFeedRanges(
Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) {
final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v;
if (partitionKeyRangeList == null) {
request.forceNameCacheRefresh = true;
throw new InvalidPartitionException();
}
List<FeedRange> feedRanges = new ArrayList<>();
partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange)));
return feedRanges;
}
private static FeedRange toFeedRange(PartitionKeyRange pkRange) {
return new FeedRangeEpkImpl(pkRange.toRange());
}
} |
Still process id with clientIdGenerator client id will help us in figuring out that user is not using singleton, whole idea of client id was to see if user is creating single or multiple client in a process. This is not related to you VmId change , but now we are here , good to have this change ? | public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) {
try {
this.httpClientInterceptor = httpClientInterceptor;
if (httpClientInterceptor != null) {
this.reactorHttpClient = httpClientInterceptor.apply(httpClient());
}
this.gatewayProxy = createRxGatewayProxy(this.sessionContainer,
this.consistencyLevel,
this.queryCompatibilityMode,
this.userAgentContainer,
this.globalEndpointManager,
this.reactorHttpClient,
this.apiType);
this.globalEndpointManager.init();
this.initializeGatewayConfigurationReader();
if (metadataCachesSnapshot != null) {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy,
metadataCachesSnapshot.getCollectionInfoByNameCache(),
metadataCachesSnapshot.getCollectionInfoByIdCache()
);
} else {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy);
}
this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy);
this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this,
collectionCache);
updateGatewayProxy();
clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(),
ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(),
connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(),
null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions());
clientTelemetry.init();
if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) {
this.storeModel = this.gatewayProxy;
} else {
this.initializeDirectConnectivity();
}
this.retryPolicy.setRxCollectionCache(this.collectionCache);
} catch (Exception e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
} | clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(), | public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) {
try {
this.httpClientInterceptor = httpClientInterceptor;
if (httpClientInterceptor != null) {
this.reactorHttpClient = httpClientInterceptor.apply(httpClient());
}
this.gatewayProxy = createRxGatewayProxy(this.sessionContainer,
this.consistencyLevel,
this.queryCompatibilityMode,
this.userAgentContainer,
this.globalEndpointManager,
this.reactorHttpClient,
this.apiType);
this.globalEndpointManager.init();
this.initializeGatewayConfigurationReader();
if (metadataCachesSnapshot != null) {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy,
metadataCachesSnapshot.getCollectionInfoByNameCache(),
metadataCachesSnapshot.getCollectionInfoByIdCache()
);
} else {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy);
}
this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy);
this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this,
collectionCache);
updateGatewayProxy();
clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(),
ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(),
connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(),
null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions());
clientTelemetry.init();
if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) {
this.storeModel = this.gatewayProxy;
} else {
this.initializeDirectConnectivity();
}
this.retryPolicy.setRxCollectionCache(this.collectionCache);
} catch (Exception e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
} | class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener,
DiagnosticsClientContext {
private static final String tempMachineId = "uuid:" + UUID.randomUUID();
private static final AtomicInteger activeClientsCnt = new AtomicInteger(0);
private static final AtomicInteger clientIdGenerator = new AtomicInteger(0);
private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>(
PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey,
PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false);
private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " +
"ParallelDocumentQueryExecutioncontext, but not used";
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper();
private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer();
private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class);
private final String masterKeyOrResourceToken;
private final URI serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel consistencyLevel;
private final BaseAuthorizationTokenProvider authorizationTokenProvider;
private final UserAgentContainer userAgentContainer;
private final boolean hasAuthKeyResourceToken;
private final Configs configs;
private final boolean connectionSharingAcrossClientsEnabled;
private AzureKeyCredential credential;
private final TokenCredential tokenCredential;
private String[] tokenCredentialScopes;
private SimpleTokenCache tokenCredentialCache;
private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver;
AuthorizationTokenType authorizationTokenType;
private SessionContainer sessionContainer;
private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY;
private RxClientCollectionCache collectionCache;
private RxStoreModel gatewayProxy;
private RxStoreModel storeModel;
private GlobalAddressResolver addressResolver;
private RxPartitionKeyRangeCache partitionKeyRangeCache;
private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap;
private final boolean contentResponseOnWriteEnabled;
private Map<String, PartitionedQueryExecutionInfo> queryPlanCache;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final int clientId;
private ClientTelemetry clientTelemetry;
private ApiType apiType;
private IRetryPolicyFactory resetSessionTokenRetryPolicy;
/**
* Compatibility mode: Allows to specify compatibility mode used by client when
* making query requests. Should be removed when application/sql is no longer
* supported.
*/
private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default;
private final GlobalEndpointManager globalEndpointManager;
private final RetryPolicy retryPolicy;
private HttpClient reactorHttpClient;
private Function<HttpClient, HttpClient> httpClientInterceptor;
private volatile boolean useMultipleWriteLocations;
private StoreClientFactory storeClientFactory;
private GatewayServiceConfigurationReader gatewayConfigurationReader;
private final DiagnosticsClientConfig diagnosticsClientConfig;
private final AtomicBoolean throughputControlEnabled;
private ThroughputControlStore throughputControlStore;
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
private RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
if (permissionFeed != null && permissionFeed.size() > 0) {
this.resourceTokensMap = new HashMap<>();
for (Permission permission : permissionFeed) {
String[] segments = StringUtils.split(permission.getResourceLink(),
Constants.Properties.PATH_SEPARATOR.charAt(0));
if (segments.length <= 0) {
throw new IllegalArgumentException("resourceLink");
}
List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null;
PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false);
if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) {
throw new IllegalArgumentException(permission.getResourceLink());
}
partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName);
if (partitionKeyAndResourceTokenPairs == null) {
partitionKeyAndResourceTokenPairs = new ArrayList<>();
this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs);
}
PartitionKey partitionKey = permission.getResourcePartitionKey();
partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair(
partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty,
permission.getToken()));
logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]",
pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken());
}
if(this.resourceTokensMap.isEmpty()) {
throw new IllegalArgumentException("permissionFeed");
}
String firstToken = permissionFeed.get(0).getToken();
if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) {
this.firstResourceTokenFromPermissionFeed = firstToken;
}
}
}
RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
activeClientsCnt.incrementAndGet();
this.clientId = clientIdGenerator.incrementAndGet();
this.diagnosticsClientConfig = new DiagnosticsClientConfig();
this.diagnosticsClientConfig.withClientId(this.clientId);
this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt);
this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled);
this.diagnosticsClientConfig.withConsistency(consistencyLevel);
this.throughputControlEnabled = new AtomicBoolean(false);
logger.info(
"Initializing DocumentClient [{}] with"
+ " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]",
this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol());
try {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
this.configs = configs;
this.masterKeyOrResourceToken = masterKeyOrResourceToken;
this.serviceEndpoint = serviceEndpoint;
this.credential = credential;
this.tokenCredential = tokenCredential;
this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled;
this.authorizationTokenType = AuthorizationTokenType.Invalid;
if (this.credential != null) {
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.authorizationTokenProvider = null;
hasAuthKeyResourceToken = true;
this.authorizationTokenType = AuthorizationTokenType.ResourceToken;
} else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken);
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else {
hasAuthKeyResourceToken = false;
this.authorizationTokenProvider = null;
if (tokenCredential != null) {
this.tokenCredentialScopes = new String[] {
serviceEndpoint.getScheme() + ":
};
this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential
.getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes)));
this.authorizationTokenType = AuthorizationTokenType.AadToken;
}
}
if (connectionPolicy != null) {
this.connectionPolicy = connectionPolicy;
} else {
this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig());
}
this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode());
this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled());
this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled());
this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions());
this.diagnosticsClientConfig.withMachineId(tempMachineId);
boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled);
this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing);
this.consistencyLevel = consistencyLevel;
this.userAgentContainer = new UserAgentContainer();
String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix();
if (userAgentSuffix != null && userAgentSuffix.length() > 0) {
userAgentContainer.setSuffix(userAgentSuffix);
}
this.httpClientInterceptor = null;
this.reactorHttpClient = httpClient();
this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs);
this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy);
this.resetSessionTokenRetryPolicy = retryPolicy;
CpuMemoryMonitor.register(this);
this.queryPlanCache = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE));
this.apiType = apiType;
} catch (RuntimeException e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
}
@Override
public DiagnosticsClientConfig getConfig() {
return diagnosticsClientConfig;
}
@Override
public CosmosDiagnostics createDiagnostics() {
return BridgeInternal.createCosmosDiagnostics(this, this.globalEndpointManager);
}
private void initializeGatewayConfigurationReader() {
this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager);
DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount();
if (databaseAccount == null) {
logger.error("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
throw new RuntimeException("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
}
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount);
}
private void updateGatewayProxy() {
((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader);
((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache);
((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache);
((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations);
}
public void serialize(CosmosClientMetadataCachesSnapshot state) {
RxCollectionCache.serialize(state, this.collectionCache);
}
private void initializeDirectConnectivity() {
this.addressResolver = new GlobalAddressResolver(this,
this.reactorHttpClient,
this.globalEndpointManager,
this.configs.getProtocol(),
this,
this.collectionCache,
this.partitionKeyRangeCache,
userAgentContainer,
null,
this.connectionPolicy,
this.apiType);
this.storeClientFactory = new StoreClientFactory(
this.addressResolver,
this.diagnosticsClientConfig,
this.configs,
this.connectionPolicy,
this.userAgentContainer,
this.connectionSharingAcrossClientsEnabled,
this.clientTelemetry
);
this.createStoreModel(true);
}
DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() {
return new DatabaseAccountManagerInternal() {
@Override
public URI getServiceEndpoint() {
return RxDocumentClientImpl.this.getServiceEndpoint();
}
@Override
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
logger.info("Getting database account endpoint from {}", endpoint);
return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return RxDocumentClientImpl.this.getConnectionPolicy();
}
};
}
RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer,
ConsistencyLevel consistencyLevel,
QueryCompatibilityMode queryCompatibilityMode,
UserAgentContainer userAgentContainer,
GlobalEndpointManager globalEndpointManager,
HttpClient httpClient,
ApiType apiType) {
return new RxGatewayStoreModel(
this,
sessionContainer,
consistencyLevel,
queryCompatibilityMode,
userAgentContainer,
globalEndpointManager,
httpClient,
apiType);
}
private HttpClient httpClient() {
HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs)
.withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout())
.withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize())
.withProxy(this.connectionPolicy.getProxy())
.withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout());
if (connectionSharingAcrossClientsEnabled) {
return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig);
} else {
diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig);
return HttpClient.createFixed(httpClientConfig);
}
}
private void createStoreModel(boolean subscribeRntbdStatus) {
StoreClient storeClient = this.storeClientFactory.createStoreClient(this,
this.addressResolver,
this.sessionContainer,
this.gatewayConfigurationReader,
this,
this.useMultipleWriteLocations
);
this.storeModel = new ServerStoreModel(storeClient);
}
@Override
public URI getServiceEndpoint() {
return this.serviceEndpoint;
}
@Override
public URI getWriteEndpoint() {
return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null);
}
@Override
public URI getReadEndpoint() {
return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return this.connectionPolicy;
}
@Override
public boolean isContentResponseOnWriteEnabled() {
return contentResponseOnWriteEnabled;
}
@Override
public ConsistencyLevel getConsistencyLevel() {
return consistencyLevel;
}
@Override
public ClientTelemetry getClientTelemetry() {
return this.clientTelemetry;
}
@Override
public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (database == null) {
throw new IllegalArgumentException("Database");
}
logger.debug("Creating a Database. id: [{}]", database.getId());
validateResource(database);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Reading a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT);
}
private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) {
switch (resourceTypeEnum) {
case Database:
return Paths.DATABASES_ROOT;
case DocumentCollection:
return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT);
case Document:
return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT);
case Offer:
return Paths.OFFERS_ROOT;
case User:
return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT);
case ClientEncryptionKey:
return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
case Permission:
return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT);
case Attachment:
return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT);
case StoredProcedure:
return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
case Trigger:
return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT);
case UserDefinedFunction:
return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
case Conflict:
return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT);
default:
throw new IllegalArgumentException("resource type not supported");
}
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) {
if (options == null) {
return null;
}
return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options);
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) {
if (options == null) {
return null;
}
return options.getOperationContextAndListenerTuple();
}
private <T extends Resource> Flux<FeedResponse<T>> createQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum) {
String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum);
UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getCorrelationActivityId(options);
UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ?
correlationActivityIdOfRequestOptions : Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this,
getOperationContextAndListenerTuple(options));
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> createQueryInternal(
resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId),
invalidPartitionExceptionRetryPolicy);
}
private <T extends Resource> Flux<FeedResponse<T>> createQueryInternal(
String resourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
IDocumentQueryClient queryClient,
UUID activityId) {
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory
.createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery,
options, resourceLink, false, activityId,
Configs.isQueryPlanCachingEnabled(), queryPlanCache);
AtomicBoolean isFirstResponse = new AtomicBoolean(true);
return executionContext.flatMap(iDocumentQueryExecutionContext -> {
QueryInfo queryInfo = null;
if (iDocumentQueryExecutionContext instanceof PipelinedDocumentQueryExecutionContext) {
queryInfo = ((PipelinedDocumentQueryExecutionContext<T>) iDocumentQueryExecutionContext).getQueryInfo();
}
QueryInfo finalQueryInfo = queryInfo;
return iDocumentQueryExecutionContext.executeAsync()
.map(tFeedResponse -> {
if (finalQueryInfo != null) {
if (finalQueryInfo.hasSelectValue()) {
ModelBridgeInternal
.addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo);
}
if (isFirstResponse.compareAndSet(true, false)) {
ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse,
finalQueryInfo.getQueryPlanDiagnosticsContext());
}
}
return tFeedResponse;
});
});
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) {
return queryDatabases(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database);
}
@Override
public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink,
DocumentCollection collection, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink,
DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink,
collection.getId());
validateResource(collection);
String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
});
} catch (Exception e) {
logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Replacing a Collection. id: [{}]", collection.getId());
validateResource(collection);
String path = Utils.joinPath(collection.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
if (resourceResponse.getResource() != null) {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
}
});
} catch (Exception e) {
logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.DELETE)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated));
}
private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated ->
this.getStoreProxy(requestPopulated).processMessage(requestPopulated)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
));
}
@Override
public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class,
Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection);
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection);
}
private static String serializeProcedureParams(List<Object> objectArray) {
String[] stringArray = new String[objectArray.size()];
for (int i = 0; i < objectArray.size(); ++i) {
Object object = objectArray.get(i);
if (object instanceof JsonSerializable) {
stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object);
} else {
try {
stringArray[i] = mapper.writeValueAsString(object);
} catch (IOException e) {
throw new IllegalArgumentException("Can't serialize the object into the json string", e);
}
}
}
return String.format("[%s]", StringUtils.join(stringArray, ","));
}
private static void validateResource(Resource resource) {
if (!StringUtils.isEmpty(resource.getId())) {
if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 ||
resource.getId().indexOf('?') != -1 || resource.getId().indexOf('
throw new IllegalArgumentException("Id contains illegal chars.");
}
if (resource.getId().endsWith(" ")) {
throw new IllegalArgumentException("Id ends with a space.");
}
}
}
private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) {
Map<String, String> headers = new HashMap<>();
if (this.useMultipleWriteLocations) {
headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString());
}
if (consistencyLevel != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString());
}
if (options == null) {
if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
return headers;
}
Map<String, String> customOptions = options.getHeaders();
if (customOptions != null) {
headers.putAll(customOptions);
}
boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled;
if (options.isContentResponseOnWriteEnabled() != null) {
contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled();
}
if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
if (options.getIfMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag());
}
if(options.getIfNoneMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag());
}
if (options.getConsistencyLevel() != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString());
}
if (options.getIndexingDirective() != null) {
headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString());
}
if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) {
String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude);
}
if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) {
String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude);
}
if (!Strings.isNullOrEmpty(options.getSessionToken())) {
headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken());
}
if (options.getResourceTokenExpirySeconds() != null) {
headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY,
String.valueOf(options.getResourceTokenExpirySeconds()));
}
if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString());
} else if (options.getOfferType() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType());
}
if (options.getOfferThroughput() == null) {
if (options.getThroughputProperties() != null) {
Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties());
final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings();
OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null;
if (offerAutoscaleSettings != null) {
autoscaleAutoUpgradeProperties
= offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties();
}
if (offer.hasOfferThroughput() &&
(offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 ||
autoscaleAutoUpgradeProperties != null &&
autoscaleAutoUpgradeProperties
.getAutoscaleThroughputProperties()
.getIncrementPercent() >= 0)) {
throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with "
+ "fixed offer");
}
if (offer.hasOfferThroughput()) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput()));
} else if (offer.getOfferAutoScaleSettings() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS,
ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings()));
}
}
}
if (options.isQuotaInfoEnabled()) {
headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true));
}
if (options.isScriptLoggingEnabled()) {
headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true));
}
if (options.getDedicatedGatewayRequestOptions() != null &&
options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) {
headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS,
String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions())));
}
return headers;
}
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return this.resetSessionTokenRetryPolicy;
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Document document,
RequestOptions options) {
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs
.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object document,
RequestOptions options,
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) {
return collectionObs.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private void addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object objectDoc, RequestOptions options,
DocumentCollection collection) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
PartitionKeyInternal partitionKeyInternal = null;
if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else if (options != null && options.getPartitionKey() != null) {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey());
} else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) {
partitionKeyInternal = PartitionKeyInternal.getEmpty();
} else if (contentAsByteBuffer != null || objectDoc != null) {
InternalObjectNode internalObjectNode;
if (objectDoc instanceof InternalObjectNode) {
internalObjectNode = (InternalObjectNode) objectDoc;
} else if (objectDoc instanceof ObjectNode) {
internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc);
} else if (contentAsByteBuffer != null) {
contentAsByteBuffer.rewind();
internalObjectNode = new InternalObjectNode(contentAsByteBuffer);
} else {
throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null");
}
Instant serializationStartTime = Instant.now();
partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTime,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION
);
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
} else {
throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation.");
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
}
public static PartitionKeyInternal extractPartitionKeyValueFromDocument(
InternalObjectNode document,
PartitionKeyDefinition partitionKeyDefinition) {
if (partitionKeyDefinition != null) {
switch (partitionKeyDefinition.getKind()) {
case HASH:
String path = partitionKeyDefinition.getPaths().iterator().next();
List<String> parts = PathParser.getPathParts(path);
if (parts.size() >= 1) {
Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts);
if (value == null || value.getClass() == ObjectNode.class) {
value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
}
if (value instanceof PartitionKeyInternal) {
return (PartitionKeyInternal) value;
} else {
return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false);
}
}
break;
case MULTI_HASH:
Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()];
for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){
String partitionPath = partitionKeyDefinition.getPaths().get(pathIter);
List<String> partitionPathParts = PathParser.getPathParts(partitionPath);
partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts);
}
return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false);
default:
throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind());
}
}
return null;
}
private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
Object document,
RequestOptions options,
boolean disableAutomaticIdGeneration,
OperationType operationType) {
if (StringUtils.isEmpty(documentCollectionLink)) {
throw new IllegalArgumentException("documentCollectionLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Document, path, requestHeaders, options, content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return addPartitionKeyInformation(request, content, document, options, collectionObs);
}
private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink");
checkNotNull(serverBatchRequest, "expected non null serverBatchRequest");
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody()));
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Batch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> {
addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v);
return request;
});
}
private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request,
ServerBatchRequest serverBatchRequest,
DocumentCollection collection) {
if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) {
PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue();
PartitionKeyInternal partitionKeyInternal;
if (partitionKey.equals(PartitionKey.NONE)) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey);
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
} else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) {
request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId()));
} else {
throw new UnsupportedOperationException("Unknown Server request.");
}
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString());
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch()));
request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError()));
request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size());
return request;
}
private Mono<RxDocumentServiceRequest> populateHeaders(RxDocumentServiceRequest request, RequestVerb httpMethod) {
request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123());
if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null
|| this.cosmosAuthorizationTokenResolver != null || this.credential != null) {
String resourceName = request.getResourceAddress();
String authorization = this.getUserAuthorizationToken(
resourceName, request.getResourceType(), httpMethod, request.getHeaders(),
AuthorizationTokenType.PrimaryMasterKey, request.properties);
try {
authorization = URLEncoder.encode(authorization, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Failed to encode authtoken.", e);
}
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
}
if (this.apiType != null) {
request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString());
}
if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod))
&& !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
}
if (RequestVerb.PATCH.equals(httpMethod) &&
!request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH);
}
if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) {
request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
}
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
if (this.requiresFeedRangeFiltering(request)) {
return request.getFeedRange()
.populateFeedRangeFilteringHeaders(
this.getPartitionKeyRangeCache(),
request,
this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request))
.flatMap(this::populateAuthorizationHeader);
}
return this.populateAuthorizationHeader(request);
}
private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) {
if (request.getResourceType() != ResourceType.Document &&
request.getResourceType() != ResourceType.Conflict) {
return false;
}
switch (request.getOperationType()) {
case ReadFeed:
case Query:
case SqlQuery:
return request.getFeedRange() != null;
default:
return false;
}
}
@Override
public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) {
if (request == null) {
throw new IllegalArgumentException("request");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return request;
});
} else {
return Mono.just(request);
}
}
@Override
public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) {
if (httpHeaders == null) {
throw new IllegalArgumentException("httpHeaders");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return httpHeaders;
});
}
return Mono.just(httpHeaders);
}
@Override
public AuthorizationTokenType getAuthorizationTokenType() {
return this.authorizationTokenType;
}
@Override
public String getUserAuthorizationToken(String resourceName,
ResourceType resourceType,
RequestVerb requestVerb,
Map<String, String> headers,
AuthorizationTokenType tokenType,
Map<String, Object> properties) {
if (this.cosmosAuthorizationTokenResolver != null) {
return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(),
properties != null ? Collections.unmodifiableMap(properties) : null);
} else if (credential != null) {
return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName,
resourceType, headers);
} else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) {
return masterKeyOrResourceToken;
} else {
assert resourceTokensMap != null;
if(resourceType.equals(ResourceType.DatabaseAccount)) {
return this.firstResourceTokenFromPermissionFeed;
}
return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers);
}
}
private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) {
CosmosResourceType cosmosResourceType =
ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString());
if (cosmosResourceType == null) {
return CosmosResourceType.SYSTEM;
}
return cosmosResourceType;
}
void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) {
this.sessionContainer.setSessionToken(request, response.getResponseHeaders());
}
private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
Map<String, String> headers = requestPopulated.getHeaders();
assert (headers != null);
headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true");
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
);
});
}
private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.PUT)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PATCH);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(request).processMessage(request);
}
@Override
public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) {
try {
logger.debug("Creating a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Create);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance);
}
private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Upsert);
Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = Utils.getCollectionName(documentLink);
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Document typedDocument = documentFromObject(document, mapper);
return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = document.getSelfLink();
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (document == null) {
throw new IllegalArgumentException("document");
}
return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a database due to [{}]", e.getMessage());
return Mono.error(e);
}
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink,
Document document,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
if (document == null) {
throw new IllegalArgumentException("document");
}
logger.debug("Replacing a Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = serializeJsonToByteBuffer(document);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs);
return requestObs.flatMap(req -> replace(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> patchDocument(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink");
checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations");
logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options));
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Patch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(
request,
null,
null,
options,
collectionObs);
return requestObs.flatMap(req -> patch(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy);
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Deleting a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs);
return requestObs.flatMap(req -> this
.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> this
.deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting documents due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Reading a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> {
return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Document>> readDocuments(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return queryDocuments(collectionLink, "SELECT * FROM r", options);
}
@Override
public <T> Mono<FeedResponse<T>> readMany(
List<CosmosItemIdentity> itemIdentityList,
String collectionLink,
CosmosQueryRequestOptions options,
Class<T> klass) {
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink, null
);
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request);
return collectionObs
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache
.tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null);
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap =
new HashMap<>();
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
itemIdentityList
.forEach(itemIdentity -> {
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(
itemIdentity.getPartitionKey()),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
if (partitionRangeItemKeyMap.get(range) == null) {
List<CosmosItemIdentity> list = new ArrayList<>();
list.add(itemIdentity);
partitionRangeItemKeyMap.put(range, list);
} else {
List<CosmosItemIdentity> pairs =
partitionRangeItemKeyMap.get(range);
pairs.add(itemIdentity);
partitionRangeItemKeyMap.put(range, pairs);
}
});
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap;
rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap,
collection.getPartitionKey());
return createReadManyQuery(
resourceLink,
new SqlQuerySpec(DUMMY_SQL_QUERY),
options,
Document.class,
ResourceType.Document,
collection,
Collections.unmodifiableMap(rangeQueryMap))
.collectList()
.map(feedList -> {
List<T> finalList = new ArrayList<>();
HashMap<String, String> headers = new HashMap<>();
ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>();
double requestCharge = 0;
for (FeedResponse<Document> page : feedList) {
ConcurrentMap<String, QueryMetrics> pageQueryMetrics =
ModelBridgeInternal.queryMetrics(page);
if (pageQueryMetrics != null) {
pageQueryMetrics.forEach(
aggregatedQueryMetrics::putIfAbsent);
}
requestCharge += page.getRequestCharge();
finalList.addAll(page.getResults().stream().map(document ->
ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList()));
}
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double
.toString(requestCharge));
FeedResponse<T> frp = BridgeInternal
.createFeedResponse(finalList, headers);
return frp;
});
});
}
);
}
private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap(
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap,
PartitionKeyDefinition partitionKeyDefinition) {
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>();
String partitionKeySelector = createPkSelector(partitionKeyDefinition);
for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) {
SqlQuerySpec sqlQuerySpec;
if (partitionKeySelector.equals("[\"id\"]")) {
sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector);
} else {
sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector);
}
rangeQueryMap.put(entry.getKey(), sqlQuerySpec);
}
return rangeQueryMap;
}
private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(
List<CosmosItemIdentity> idPartitionKeyPairList,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( ");
for (int i = 0; i < idPartitionKeyPairList.size(); i++) {
CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i);
String idValue = itemIdentity.getId();
String idParamName = "@param" + i;
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
if (!Objects.equals(idValue, pkValue)) {
continue;
}
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append(idParamName);
if (i < idPartitionKeyPairList.size() - 1) {
queryStringBuilder.append(", ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE ( ");
for (int i = 0; i < itemIdentities.size(); i++) {
CosmosItemIdentity itemIdentity = itemIdentities.get(i);
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
String pkParamName = "@param" + (2 * i);
parameters.add(new SqlParameter(pkParamName, pkValue));
String idValue = itemIdentity.getId();
String idParamName = "@param" + (2 * i + 1);
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append("(");
queryStringBuilder.append("c.id = ");
queryStringBuilder.append(idParamName);
queryStringBuilder.append(" AND ");
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
queryStringBuilder.append(" )");
if (i < itemIdentities.size() - 1) {
queryStringBuilder.append(" OR ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) {
return partitionKeyDefinition.getPaths()
.stream()
.map(pathPart -> StringUtils.substring(pathPart, 1))
.map(pathPart -> StringUtils.replace(pathPart, "\"", "\\"))
.map(part -> "[\"" + part + "\"]")
.collect(Collectors.joining());
}
private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
DocumentCollection collection,
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) {
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(),
sqlQuery,
rangeQueryMap,
options,
collection.getResourceId(),
parentResourceLink,
activityId,
klass,
resourceTypeEnum);
return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync);
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, String query, CosmosQueryRequestOptions options) {
return queryDocuments(collectionLink, new SqlQuerySpec(query), options);
}
private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return new IDocumentQueryClient () {
@Override
public RxCollectionCache getCollectionCache() {
return RxDocumentClientImpl.this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return RxDocumentClientImpl.this.partitionKeyRangeCache;
}
@Override
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy;
}
@Override
public ConsistencyLevel getDefaultConsistencyLevelAsync() {
return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel();
}
@Override
public ConsistencyLevel getDesiredConsistencyLevelAsync() {
return RxDocumentClientImpl.this.consistencyLevel;
}
@Override
public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) {
if (operationContextAndListenerTuple == null) {
return RxDocumentClientImpl.this.query(request).single();
} else {
final OperationListener listener =
operationContextAndListenerTuple.getOperationListener();
final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext();
request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId());
listener.requestListener(operationContext, request);
return RxDocumentClientImpl.this.query(request).single().doOnNext(
response -> listener.responseListener(operationContext, response)
).doOnError(
ex -> listener.exceptionListener(operationContext, ex)
);
}
}
@Override
public QueryCompatibilityMode getQueryCompatibilityMode() {
return QueryCompatibilityMode.Default;
}
@Override
public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) {
return null;
}
};
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
SqlQuerySpecLogger.getInstance().logQuery(querySpec);
return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document);
}
@Override
public Flux<FeedResponse<Document>> queryDocumentChangeFeed(
final DocumentCollection collection,
final CosmosChangeFeedRequestOptions changeFeedOptions) {
checkNotNull(collection, "Argument 'collection' must not be null.");
ChangeFeedQueryImpl<Document> changeFeedQueryImpl = new ChangeFeedQueryImpl<>(
this,
ResourceType.Document,
Document.class,
collection.getAltLink(),
collection.getResourceId(),
changeFeedOptions);
return changeFeedQueryImpl.executeAsync();
}
@Override
public Flux<FeedResponse<Document>> readAllDocuments(
String collectionLink,
PartitionKey partitionKey,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (partitionKey == null) {
throw new IllegalArgumentException("partitionKey");
}
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null
);
Flux<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request).flux();
return collectionObs.flatMap(documentCollectionResourceResponse -> {
DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
String pkSelector = createPkSelector(pkDefinition);
SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector);
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
final CosmosQueryRequestOptions effectiveOptions =
ModelBridgeInternal.createQueryRequestOptions(options);
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> {
Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache
.tryLookupAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null).flux();
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(partitionKey),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
return createQueryInternal(
resourceLink,
querySpec,
ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()),
Document.class,
ResourceType.Document,
queryClient,
activityId);
});
},
invalidPartitionExceptionRetryPolicy);
});
}
@Override
public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() {
return queryPlanCache;
}
@Override
public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class,
Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT));
}
private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
validateResource(storedProcedure);
String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType,
ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
return request;
}
private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (udf == null) {
throw new IllegalArgumentException("udf");
}
validateResource(udf);
String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Create);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId());
RxDocumentClientImpl.validateResource(storedProcedure);
String path = Utils.joinPath(storedProcedure.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class,
Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
List<Object> procedureParams) {
return this.executeStoredProcedure(storedProcedureLink, null, procedureParams);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy);
}
@Override
public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy);
}
private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) {
try {
logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript);
requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ExecuteJavaScript,
ResourceType.StoredProcedure, path,
procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "",
requestHeaders, options);
if (retryPolicy != null) {
retryPolicy.onBeforeSendRequest(request);
}
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options))
.map(response -> {
this.captureSessionToken(request, response);
return toStoredProcedureResponse(response);
}));
} catch (Exception e) {
logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
DocumentClientRetryPolicy requestRetryPolicy,
boolean disableAutomaticIdGeneration) {
try {
logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size());
Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true));
} catch (Exception ex) {
logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex);
return Mono.error(ex);
}
}
@Override
public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path,
trigger, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId());
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(trigger.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Trigger, Trigger.class,
Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryTriggers(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger);
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (udf == null) {
throw new IllegalArgumentException("udf");
}
logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId());
validateResource(udf);
String path = Utils.joinPath(udf.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class,
Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
String query, CosmosQueryRequestOptions options) {
return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction);
}
@Override
public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Conflict, Conflict.class,
Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryConflicts(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict);
}
@Override
public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (user == null) {
throw new IllegalArgumentException("user");
}
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.User, path, user, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (user == null) {
throw new IllegalArgumentException("user");
}
logger.debug("Replacing a User. user id [{}]", user.getId());
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(user.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.User, path, user, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Deleting a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Reading a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.User, User.class,
Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) {
return queryUsers(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User);
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(clientEncryptionKeyLink)) {
throw new IllegalArgumentException("clientEncryptionKeyLink");
}
logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink);
String path = Utils.joinPath(clientEncryptionKeyLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink,
ClientEncryptionKey clientEncryptionKey, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId());
RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey,
String nameBasedLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey,
nameBasedLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId());
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(nameBasedLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey,
OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders,
options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class,
Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey);
}
@Override
public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy());
}
private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
if (permission == null) {
throw new IllegalArgumentException("permission");
}
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Permission, path, permission, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (permission == null) {
throw new IllegalArgumentException("permission");
}
logger.debug("Replacing a Permission. permission id [{}]", permission.getId());
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(permission.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Reading a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
return readFeed(options, ResourceType.Permission, Permission.class,
Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query,
CosmosQueryRequestOptions options) {
return queryPermissions(userLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission);
}
@Override
public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
if (offer == null) {
throw new IllegalArgumentException("offer");
}
logger.debug("Replacing an Offer. offer id [{}]", offer.getId());
RxDocumentClientImpl.validateResource(offer);
String path = Utils.joinPath(offer.getSelfLink(), null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace,
ResourceType.Offer, path, offer, null, null);
return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Offer>> readOffer(String offerLink) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(offerLink)) {
throw new IllegalArgumentException("offerLink");
}
logger.debug("Reading an Offer. offerLink [{}]", offerLink);
String path = Utils.joinPath(offerLink, null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Offer, Offer.class,
Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null));
}
private <T extends Resource> Flux<FeedResponse<T>> readFeed(CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options);
int maxPageSize = maxItemCount != null ? maxItemCount : -1;
final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options;
DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> {
Map<String, String> requestHeaders = new HashMap<>();
if (continuationToken != null) {
requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken);
}
requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize));
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions);
retryPolicy.onBeforeSendRequest(request);
return request;
};
Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper
.inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)),
retryPolicy);
return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, maxPageSize);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) {
return queryOffers(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer);
}
@Override
public Mono<DatabaseAccount> getDatabaseAccount() {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy),
documentClientRetryPolicy);
}
@Override
public DatabaseAccount getLatestDatabaseAccount() {
return this.globalEndpointManager.getLatestDatabaseAccount();
}
private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Getting Database Account");
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read,
ResourceType.DatabaseAccount, "",
(HashMap<String, String>) null,
null);
return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount);
} catch (Exception e) {
logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Object getSession() {
return this.sessionContainer;
}
public void setSession(Object sessionContainer) {
this.sessionContainer = (SessionContainer) sessionContainer;
}
@Override
public RxClientCollectionCache getCollectionCache() {
return this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return partitionKeyRangeCache;
}
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
return Flux.defer(() -> {
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null);
return this.populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
requestPopulated.setEndpointOverride(endpoint);
return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> {
String message = String.format("Failed to retrieve database account information. %s",
e.getCause() != null
? e.getCause().toString()
: e.toString());
logger.warn(message);
}).map(rsp -> rsp.getResource(DatabaseAccount.class))
.doOnNext(databaseAccount ->
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled()
&& BridgeInternal.isEnableMultipleWriteLocations(databaseAccount));
});
});
}
/**
* Certain requests must be routed through gateway even when the client connectivity mode is direct.
*
* @param request
* @return RxStoreModel
*/
private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) {
if (request.UseGatewayMode) {
return this.gatewayProxy;
}
ResourceType resourceType = request.getResourceType();
OperationType operationType = request.getOperationType();
if (resourceType == ResourceType.Offer ||
resourceType == ResourceType.ClientEncryptionKey ||
resourceType.isScript() && operationType != OperationType.ExecuteJavaScript ||
resourceType == ResourceType.PartitionKeyRange ||
resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) {
return this.gatewayProxy;
}
if (operationType == OperationType.Create
|| operationType == OperationType.Upsert) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection ||
resourceType == ResourceType.Permission) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Delete) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Replace) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Read) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else {
if ((operationType == OperationType.Query ||
operationType == OperationType.SqlQuery ||
operationType == OperationType.ReadFeed) &&
Utils.isCollectionChild(request.getResourceType())) {
if (request.getPartitionKeyRangeIdentity() == null &&
request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) {
return this.gatewayProxy;
}
}
return this.storeModel;
}
}
@Override
public void close() {
logger.info("Attempting to close client {}", this.clientId);
if (!closed.getAndSet(true)) {
this.activeClientsCnt.decrementAndGet();
logger.info("Shutting down ...");
logger.info("Closing Global Endpoint Manager ...");
LifeCycleUtils.closeQuietly(this.globalEndpointManager);
logger.info("Closing StoreClientFactory ...");
LifeCycleUtils.closeQuietly(this.storeClientFactory);
logger.info("Shutting down reactorHttpClient ...");
LifeCycleUtils.closeQuietly(this.reactorHttpClient);
logger.info("Shutting down CpuMonitor ...");
CpuMemoryMonitor.unregister(this);
if (this.throughputControlEnabled.get()) {
logger.info("Closing ThroughputControlStore ...");
this.throughputControlStore.close();
}
logger.info("Shutting down completed.");
} else {
logger.warn("Already shutdown!");
}
}
@Override
public ItemDeserializer getItemDeserializer() {
return this.itemDeserializer;
}
@Override
public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group can not be null");
if (this.throughputControlEnabled.compareAndSet(false, true)) {
this.throughputControlStore =
new ThroughputControlStore(
this.collectionCache,
this.connectionPolicy.getConnectionMode(),
this.partitionKeyRangeCache);
this.storeModel.enableThroughputControl(throughputControlStore);
}
this.throughputControlStore.enableThroughputControlGroup(group);
}
private static SqlQuerySpec createLogicalPartitionScanQuerySpec(
PartitionKey partitionKey,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE");
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey);
String pkParamName = "@pkValue";
parameters.add(new SqlParameter(pkParamName, pkValue));
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
@Override
public Mono<List<FeedRange>> getFeedRanges(String collectionLink) {
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
collectionLink,
new HashMap<>());
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null);
invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request);
return ObservableHelper.inlineIfPossibleAsObs(
() -> getFeedRangesInternal(request, collectionLink),
invalidPartitionExceptionRetryPolicy);
}
private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) {
logger.debug("getFeedRange collectionLink=[{}]", collectionLink);
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null,
request);
return collectionObs.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache
.tryGetOverlappingRangesAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null);
return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request));
});
}
private static List<FeedRange> toFeedRanges(
Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) {
final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v;
if (partitionKeyRangeList == null) {
request.forceNameCacheRefresh = true;
throw new InvalidPartitionException();
}
List<FeedRange> feedRanges = new ArrayList<>();
partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange)));
return feedRanges;
}
private static FeedRange toFeedRange(PartitionKeyRange pkRange) {
return new FeedRangeEpkImpl(pkRange.toRange());
}
} | class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener,
DiagnosticsClientContext {
private static final String tempMachineId = "uuid:" + UUID.randomUUID();
private static final AtomicInteger activeClientsCnt = new AtomicInteger(0);
private static final AtomicInteger clientIdGenerator = new AtomicInteger(0);
private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>(
PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey,
PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false);
private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " +
"ParallelDocumentQueryExecutioncontext, but not used";
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper();
private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer();
private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class);
private final String masterKeyOrResourceToken;
private final URI serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel consistencyLevel;
private final BaseAuthorizationTokenProvider authorizationTokenProvider;
private final UserAgentContainer userAgentContainer;
private final boolean hasAuthKeyResourceToken;
private final Configs configs;
private final boolean connectionSharingAcrossClientsEnabled;
private AzureKeyCredential credential;
private final TokenCredential tokenCredential;
private String[] tokenCredentialScopes;
private SimpleTokenCache tokenCredentialCache;
private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver;
AuthorizationTokenType authorizationTokenType;
private SessionContainer sessionContainer;
private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY;
private RxClientCollectionCache collectionCache;
private RxStoreModel gatewayProxy;
private RxStoreModel storeModel;
private GlobalAddressResolver addressResolver;
private RxPartitionKeyRangeCache partitionKeyRangeCache;
private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap;
private final boolean contentResponseOnWriteEnabled;
private Map<String, PartitionedQueryExecutionInfo> queryPlanCache;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final int clientId;
private ClientTelemetry clientTelemetry;
private ApiType apiType;
private IRetryPolicyFactory resetSessionTokenRetryPolicy;
/**
* Compatibility mode: Allows to specify compatibility mode used by client when
* making query requests. Should be removed when application/sql is no longer
* supported.
*/
private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default;
private final GlobalEndpointManager globalEndpointManager;
private final RetryPolicy retryPolicy;
private HttpClient reactorHttpClient;
private Function<HttpClient, HttpClient> httpClientInterceptor;
private volatile boolean useMultipleWriteLocations;
private StoreClientFactory storeClientFactory;
private GatewayServiceConfigurationReader gatewayConfigurationReader;
private final DiagnosticsClientConfig diagnosticsClientConfig;
private final AtomicBoolean throughputControlEnabled;
private ThroughputControlStore throughputControlStore;
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
private RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
if (permissionFeed != null && permissionFeed.size() > 0) {
this.resourceTokensMap = new HashMap<>();
for (Permission permission : permissionFeed) {
String[] segments = StringUtils.split(permission.getResourceLink(),
Constants.Properties.PATH_SEPARATOR.charAt(0));
if (segments.length <= 0) {
throw new IllegalArgumentException("resourceLink");
}
List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null;
PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false);
if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) {
throw new IllegalArgumentException(permission.getResourceLink());
}
partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName);
if (partitionKeyAndResourceTokenPairs == null) {
partitionKeyAndResourceTokenPairs = new ArrayList<>();
this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs);
}
PartitionKey partitionKey = permission.getResourcePartitionKey();
partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair(
partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty,
permission.getToken()));
logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]",
pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken());
}
if(this.resourceTokensMap.isEmpty()) {
throw new IllegalArgumentException("permissionFeed");
}
String firstToken = permissionFeed.get(0).getToken();
if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) {
this.firstResourceTokenFromPermissionFeed = firstToken;
}
}
}
RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
activeClientsCnt.incrementAndGet();
this.clientId = clientIdGenerator.incrementAndGet();
this.diagnosticsClientConfig = new DiagnosticsClientConfig();
this.diagnosticsClientConfig.withClientId(this.clientId);
this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt);
this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled);
this.diagnosticsClientConfig.withConsistency(consistencyLevel);
this.throughputControlEnabled = new AtomicBoolean(false);
logger.info(
"Initializing DocumentClient [{}] with"
+ " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]",
this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol());
try {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
this.configs = configs;
this.masterKeyOrResourceToken = masterKeyOrResourceToken;
this.serviceEndpoint = serviceEndpoint;
this.credential = credential;
this.tokenCredential = tokenCredential;
this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled;
this.authorizationTokenType = AuthorizationTokenType.Invalid;
if (this.credential != null) {
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.authorizationTokenProvider = null;
hasAuthKeyResourceToken = true;
this.authorizationTokenType = AuthorizationTokenType.ResourceToken;
} else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken);
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else {
hasAuthKeyResourceToken = false;
this.authorizationTokenProvider = null;
if (tokenCredential != null) {
this.tokenCredentialScopes = new String[] {
serviceEndpoint.getScheme() + ":
};
this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential
.getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes)));
this.authorizationTokenType = AuthorizationTokenType.AadToken;
}
}
if (connectionPolicy != null) {
this.connectionPolicy = connectionPolicy;
} else {
this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig());
}
this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode());
this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled());
this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled());
this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions());
this.diagnosticsClientConfig.withMachineId(tempMachineId);
boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled);
this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing);
this.consistencyLevel = consistencyLevel;
this.userAgentContainer = new UserAgentContainer();
String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix();
if (userAgentSuffix != null && userAgentSuffix.length() > 0) {
userAgentContainer.setSuffix(userAgentSuffix);
}
this.httpClientInterceptor = null;
this.reactorHttpClient = httpClient();
this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs);
this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy);
this.resetSessionTokenRetryPolicy = retryPolicy;
CpuMemoryMonitor.register(this);
this.queryPlanCache = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE));
this.apiType = apiType;
} catch (RuntimeException e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
}
@Override
public DiagnosticsClientConfig getConfig() {
return diagnosticsClientConfig;
}
@Override
public CosmosDiagnostics createDiagnostics() {
return BridgeInternal.createCosmosDiagnostics(this, this.globalEndpointManager);
}
private void initializeGatewayConfigurationReader() {
this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager);
DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount();
if (databaseAccount == null) {
logger.error("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
throw new RuntimeException("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
}
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount);
}
private void updateGatewayProxy() {
((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader);
((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache);
((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache);
((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations);
}
public void serialize(CosmosClientMetadataCachesSnapshot state) {
RxCollectionCache.serialize(state, this.collectionCache);
}
private void initializeDirectConnectivity() {
this.addressResolver = new GlobalAddressResolver(this,
this.reactorHttpClient,
this.globalEndpointManager,
this.configs.getProtocol(),
this,
this.collectionCache,
this.partitionKeyRangeCache,
userAgentContainer,
null,
this.connectionPolicy,
this.apiType);
this.storeClientFactory = new StoreClientFactory(
this.addressResolver,
this.diagnosticsClientConfig,
this.configs,
this.connectionPolicy,
this.userAgentContainer,
this.connectionSharingAcrossClientsEnabled,
this.clientTelemetry
);
this.createStoreModel(true);
}
DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() {
return new DatabaseAccountManagerInternal() {
@Override
public URI getServiceEndpoint() {
return RxDocumentClientImpl.this.getServiceEndpoint();
}
@Override
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
logger.info("Getting database account endpoint from {}", endpoint);
return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return RxDocumentClientImpl.this.getConnectionPolicy();
}
};
}
RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer,
ConsistencyLevel consistencyLevel,
QueryCompatibilityMode queryCompatibilityMode,
UserAgentContainer userAgentContainer,
GlobalEndpointManager globalEndpointManager,
HttpClient httpClient,
ApiType apiType) {
return new RxGatewayStoreModel(
this,
sessionContainer,
consistencyLevel,
queryCompatibilityMode,
userAgentContainer,
globalEndpointManager,
httpClient,
apiType);
}
private HttpClient httpClient() {
HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs)
.withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout())
.withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize())
.withProxy(this.connectionPolicy.getProxy())
.withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout());
if (connectionSharingAcrossClientsEnabled) {
return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig);
} else {
diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig);
return HttpClient.createFixed(httpClientConfig);
}
}
private void createStoreModel(boolean subscribeRntbdStatus) {
StoreClient storeClient = this.storeClientFactory.createStoreClient(this,
this.addressResolver,
this.sessionContainer,
this.gatewayConfigurationReader,
this,
this.useMultipleWriteLocations
);
this.storeModel = new ServerStoreModel(storeClient);
}
@Override
public URI getServiceEndpoint() {
return this.serviceEndpoint;
}
@Override
public URI getWriteEndpoint() {
return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null);
}
@Override
public URI getReadEndpoint() {
return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return this.connectionPolicy;
}
@Override
public boolean isContentResponseOnWriteEnabled() {
return contentResponseOnWriteEnabled;
}
@Override
public ConsistencyLevel getConsistencyLevel() {
return consistencyLevel;
}
@Override
public ClientTelemetry getClientTelemetry() {
return this.clientTelemetry;
}
@Override
public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (database == null) {
throw new IllegalArgumentException("Database");
}
logger.debug("Creating a Database. id: [{}]", database.getId());
validateResource(database);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Reading a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT);
}
private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) {
switch (resourceTypeEnum) {
case Database:
return Paths.DATABASES_ROOT;
case DocumentCollection:
return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT);
case Document:
return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT);
case Offer:
return Paths.OFFERS_ROOT;
case User:
return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT);
case ClientEncryptionKey:
return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
case Permission:
return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT);
case Attachment:
return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT);
case StoredProcedure:
return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
case Trigger:
return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT);
case UserDefinedFunction:
return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
case Conflict:
return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT);
default:
throw new IllegalArgumentException("resource type not supported");
}
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) {
if (options == null) {
return null;
}
return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options);
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) {
if (options == null) {
return null;
}
return options.getOperationContextAndListenerTuple();
}
private <T extends Resource> Flux<FeedResponse<T>> createQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum) {
String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum);
UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getCorrelationActivityId(options);
UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ?
correlationActivityIdOfRequestOptions : Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this,
getOperationContextAndListenerTuple(options));
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> createQueryInternal(
resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId),
invalidPartitionExceptionRetryPolicy);
}
private <T extends Resource> Flux<FeedResponse<T>> createQueryInternal(
String resourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
IDocumentQueryClient queryClient,
UUID activityId) {
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory
.createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery,
options, resourceLink, false, activityId,
Configs.isQueryPlanCachingEnabled(), queryPlanCache);
AtomicBoolean isFirstResponse = new AtomicBoolean(true);
return executionContext.flatMap(iDocumentQueryExecutionContext -> {
QueryInfo queryInfo = null;
if (iDocumentQueryExecutionContext instanceof PipelinedDocumentQueryExecutionContext) {
queryInfo = ((PipelinedDocumentQueryExecutionContext<T>) iDocumentQueryExecutionContext).getQueryInfo();
}
QueryInfo finalQueryInfo = queryInfo;
return iDocumentQueryExecutionContext.executeAsync()
.map(tFeedResponse -> {
if (finalQueryInfo != null) {
if (finalQueryInfo.hasSelectValue()) {
ModelBridgeInternal
.addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo);
}
if (isFirstResponse.compareAndSet(true, false)) {
ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse,
finalQueryInfo.getQueryPlanDiagnosticsContext());
}
}
return tFeedResponse;
});
});
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) {
return queryDatabases(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database);
}
@Override
public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink,
DocumentCollection collection, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink,
DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink,
collection.getId());
validateResource(collection);
String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
});
} catch (Exception e) {
logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Replacing a Collection. id: [{}]", collection.getId());
validateResource(collection);
String path = Utils.joinPath(collection.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
if (resourceResponse.getResource() != null) {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
}
});
} catch (Exception e) {
logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.DELETE)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated));
}
private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated ->
this.getStoreProxy(requestPopulated).processMessage(requestPopulated)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
));
}
@Override
public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class,
Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection);
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection);
}
private static String serializeProcedureParams(List<Object> objectArray) {
String[] stringArray = new String[objectArray.size()];
for (int i = 0; i < objectArray.size(); ++i) {
Object object = objectArray.get(i);
if (object instanceof JsonSerializable) {
stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object);
} else {
try {
stringArray[i] = mapper.writeValueAsString(object);
} catch (IOException e) {
throw new IllegalArgumentException("Can't serialize the object into the json string", e);
}
}
}
return String.format("[%s]", StringUtils.join(stringArray, ","));
}
private static void validateResource(Resource resource) {
if (!StringUtils.isEmpty(resource.getId())) {
if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 ||
resource.getId().indexOf('?') != -1 || resource.getId().indexOf('
throw new IllegalArgumentException("Id contains illegal chars.");
}
if (resource.getId().endsWith(" ")) {
throw new IllegalArgumentException("Id ends with a space.");
}
}
}
private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) {
Map<String, String> headers = new HashMap<>();
if (this.useMultipleWriteLocations) {
headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString());
}
if (consistencyLevel != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString());
}
if (options == null) {
if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
return headers;
}
Map<String, String> customOptions = options.getHeaders();
if (customOptions != null) {
headers.putAll(customOptions);
}
boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled;
if (options.isContentResponseOnWriteEnabled() != null) {
contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled();
}
if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
if (options.getIfMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag());
}
if(options.getIfNoneMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag());
}
if (options.getConsistencyLevel() != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString());
}
if (options.getIndexingDirective() != null) {
headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString());
}
if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) {
String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude);
}
if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) {
String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude);
}
if (!Strings.isNullOrEmpty(options.getSessionToken())) {
headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken());
}
if (options.getResourceTokenExpirySeconds() != null) {
headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY,
String.valueOf(options.getResourceTokenExpirySeconds()));
}
if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString());
} else if (options.getOfferType() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType());
}
if (options.getOfferThroughput() == null) {
if (options.getThroughputProperties() != null) {
Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties());
final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings();
OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null;
if (offerAutoscaleSettings != null) {
autoscaleAutoUpgradeProperties
= offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties();
}
if (offer.hasOfferThroughput() &&
(offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 ||
autoscaleAutoUpgradeProperties != null &&
autoscaleAutoUpgradeProperties
.getAutoscaleThroughputProperties()
.getIncrementPercent() >= 0)) {
throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with "
+ "fixed offer");
}
if (offer.hasOfferThroughput()) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput()));
} else if (offer.getOfferAutoScaleSettings() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS,
ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings()));
}
}
}
if (options.isQuotaInfoEnabled()) {
headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true));
}
if (options.isScriptLoggingEnabled()) {
headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true));
}
if (options.getDedicatedGatewayRequestOptions() != null &&
options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) {
headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS,
String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions())));
}
return headers;
}
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return this.resetSessionTokenRetryPolicy;
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Document document,
RequestOptions options) {
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs
.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object document,
RequestOptions options,
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) {
return collectionObs.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private void addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object objectDoc, RequestOptions options,
DocumentCollection collection) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
PartitionKeyInternal partitionKeyInternal = null;
if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else if (options != null && options.getPartitionKey() != null) {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey());
} else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) {
partitionKeyInternal = PartitionKeyInternal.getEmpty();
} else if (contentAsByteBuffer != null || objectDoc != null) {
InternalObjectNode internalObjectNode;
if (objectDoc instanceof InternalObjectNode) {
internalObjectNode = (InternalObjectNode) objectDoc;
} else if (objectDoc instanceof ObjectNode) {
internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc);
} else if (contentAsByteBuffer != null) {
contentAsByteBuffer.rewind();
internalObjectNode = new InternalObjectNode(contentAsByteBuffer);
} else {
throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null");
}
Instant serializationStartTime = Instant.now();
partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTime,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION
);
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
} else {
throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation.");
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
}
public static PartitionKeyInternal extractPartitionKeyValueFromDocument(
InternalObjectNode document,
PartitionKeyDefinition partitionKeyDefinition) {
if (partitionKeyDefinition != null) {
switch (partitionKeyDefinition.getKind()) {
case HASH:
String path = partitionKeyDefinition.getPaths().iterator().next();
List<String> parts = PathParser.getPathParts(path);
if (parts.size() >= 1) {
Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts);
if (value == null || value.getClass() == ObjectNode.class) {
value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
}
if (value instanceof PartitionKeyInternal) {
return (PartitionKeyInternal) value;
} else {
return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false);
}
}
break;
case MULTI_HASH:
Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()];
for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){
String partitionPath = partitionKeyDefinition.getPaths().get(pathIter);
List<String> partitionPathParts = PathParser.getPathParts(partitionPath);
partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts);
}
return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false);
default:
throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind());
}
}
return null;
}
private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
Object document,
RequestOptions options,
boolean disableAutomaticIdGeneration,
OperationType operationType) {
if (StringUtils.isEmpty(documentCollectionLink)) {
throw new IllegalArgumentException("documentCollectionLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Document, path, requestHeaders, options, content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return addPartitionKeyInformation(request, content, document, options, collectionObs);
}
private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink");
checkNotNull(serverBatchRequest, "expected non null serverBatchRequest");
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody()));
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Batch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> {
addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v);
return request;
});
}
private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request,
ServerBatchRequest serverBatchRequest,
DocumentCollection collection) {
if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) {
PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue();
PartitionKeyInternal partitionKeyInternal;
if (partitionKey.equals(PartitionKey.NONE)) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey);
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
} else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) {
request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId()));
} else {
throw new UnsupportedOperationException("Unknown Server request.");
}
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString());
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch()));
request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError()));
request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size());
return request;
}
private Mono<RxDocumentServiceRequest> populateHeaders(RxDocumentServiceRequest request, RequestVerb httpMethod) {
request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123());
if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null
|| this.cosmosAuthorizationTokenResolver != null || this.credential != null) {
String resourceName = request.getResourceAddress();
String authorization = this.getUserAuthorizationToken(
resourceName, request.getResourceType(), httpMethod, request.getHeaders(),
AuthorizationTokenType.PrimaryMasterKey, request.properties);
try {
authorization = URLEncoder.encode(authorization, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Failed to encode authtoken.", e);
}
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
}
if (this.apiType != null) {
request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString());
}
if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod))
&& !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
}
if (RequestVerb.PATCH.equals(httpMethod) &&
!request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH);
}
if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) {
request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
}
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
if (this.requiresFeedRangeFiltering(request)) {
return request.getFeedRange()
.populateFeedRangeFilteringHeaders(
this.getPartitionKeyRangeCache(),
request,
this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request))
.flatMap(this::populateAuthorizationHeader);
}
return this.populateAuthorizationHeader(request);
}
private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) {
if (request.getResourceType() != ResourceType.Document &&
request.getResourceType() != ResourceType.Conflict) {
return false;
}
switch (request.getOperationType()) {
case ReadFeed:
case Query:
case SqlQuery:
return request.getFeedRange() != null;
default:
return false;
}
}
@Override
public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) {
if (request == null) {
throw new IllegalArgumentException("request");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return request;
});
} else {
return Mono.just(request);
}
}
@Override
public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) {
if (httpHeaders == null) {
throw new IllegalArgumentException("httpHeaders");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return httpHeaders;
});
}
return Mono.just(httpHeaders);
}
@Override
public AuthorizationTokenType getAuthorizationTokenType() {
return this.authorizationTokenType;
}
@Override
public String getUserAuthorizationToken(String resourceName,
ResourceType resourceType,
RequestVerb requestVerb,
Map<String, String> headers,
AuthorizationTokenType tokenType,
Map<String, Object> properties) {
if (this.cosmosAuthorizationTokenResolver != null) {
return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(),
properties != null ? Collections.unmodifiableMap(properties) : null);
} else if (credential != null) {
return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName,
resourceType, headers);
} else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) {
return masterKeyOrResourceToken;
} else {
assert resourceTokensMap != null;
if(resourceType.equals(ResourceType.DatabaseAccount)) {
return this.firstResourceTokenFromPermissionFeed;
}
return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers);
}
}
private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) {
CosmosResourceType cosmosResourceType =
ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString());
if (cosmosResourceType == null) {
return CosmosResourceType.SYSTEM;
}
return cosmosResourceType;
}
void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) {
this.sessionContainer.setSessionToken(request, response.getResponseHeaders());
}
private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
Map<String, String> headers = requestPopulated.getHeaders();
assert (headers != null);
headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true");
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
);
});
}
private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.PUT)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PATCH);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(request).processMessage(request);
}
@Override
public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) {
try {
logger.debug("Creating a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Create);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance);
}
private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Upsert);
Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = Utils.getCollectionName(documentLink);
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Document typedDocument = documentFromObject(document, mapper);
return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = document.getSelfLink();
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (document == null) {
throw new IllegalArgumentException("document");
}
return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a database due to [{}]", e.getMessage());
return Mono.error(e);
}
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink,
Document document,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
if (document == null) {
throw new IllegalArgumentException("document");
}
logger.debug("Replacing a Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = serializeJsonToByteBuffer(document);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs);
return requestObs.flatMap(req -> replace(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> patchDocument(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink");
checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations");
logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options));
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Patch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(
request,
null,
null,
options,
collectionObs);
return requestObs.flatMap(req -> patch(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy);
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Deleting a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs);
return requestObs.flatMap(req -> this
.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> this
.deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting documents due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Reading a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> {
return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Document>> readDocuments(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return queryDocuments(collectionLink, "SELECT * FROM r", options);
}
@Override
public <T> Mono<FeedResponse<T>> readMany(
List<CosmosItemIdentity> itemIdentityList,
String collectionLink,
CosmosQueryRequestOptions options,
Class<T> klass) {
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink, null
);
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request);
return collectionObs
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache
.tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null);
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap =
new HashMap<>();
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
itemIdentityList
.forEach(itemIdentity -> {
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(
itemIdentity.getPartitionKey()),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
if (partitionRangeItemKeyMap.get(range) == null) {
List<CosmosItemIdentity> list = new ArrayList<>();
list.add(itemIdentity);
partitionRangeItemKeyMap.put(range, list);
} else {
List<CosmosItemIdentity> pairs =
partitionRangeItemKeyMap.get(range);
pairs.add(itemIdentity);
partitionRangeItemKeyMap.put(range, pairs);
}
});
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap;
rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap,
collection.getPartitionKey());
return createReadManyQuery(
resourceLink,
new SqlQuerySpec(DUMMY_SQL_QUERY),
options,
Document.class,
ResourceType.Document,
collection,
Collections.unmodifiableMap(rangeQueryMap))
.collectList()
.map(feedList -> {
List<T> finalList = new ArrayList<>();
HashMap<String, String> headers = new HashMap<>();
ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>();
double requestCharge = 0;
for (FeedResponse<Document> page : feedList) {
ConcurrentMap<String, QueryMetrics> pageQueryMetrics =
ModelBridgeInternal.queryMetrics(page);
if (pageQueryMetrics != null) {
pageQueryMetrics.forEach(
aggregatedQueryMetrics::putIfAbsent);
}
requestCharge += page.getRequestCharge();
finalList.addAll(page.getResults().stream().map(document ->
ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList()));
}
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double
.toString(requestCharge));
FeedResponse<T> frp = BridgeInternal
.createFeedResponse(finalList, headers);
return frp;
});
});
}
);
}
private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap(
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap,
PartitionKeyDefinition partitionKeyDefinition) {
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>();
String partitionKeySelector = createPkSelector(partitionKeyDefinition);
for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) {
SqlQuerySpec sqlQuerySpec;
if (partitionKeySelector.equals("[\"id\"]")) {
sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector);
} else {
sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector);
}
rangeQueryMap.put(entry.getKey(), sqlQuerySpec);
}
return rangeQueryMap;
}
private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(
List<CosmosItemIdentity> idPartitionKeyPairList,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( ");
for (int i = 0; i < idPartitionKeyPairList.size(); i++) {
CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i);
String idValue = itemIdentity.getId();
String idParamName = "@param" + i;
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
if (!Objects.equals(idValue, pkValue)) {
continue;
}
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append(idParamName);
if (i < idPartitionKeyPairList.size() - 1) {
queryStringBuilder.append(", ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE ( ");
for (int i = 0; i < itemIdentities.size(); i++) {
CosmosItemIdentity itemIdentity = itemIdentities.get(i);
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
String pkParamName = "@param" + (2 * i);
parameters.add(new SqlParameter(pkParamName, pkValue));
String idValue = itemIdentity.getId();
String idParamName = "@param" + (2 * i + 1);
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append("(");
queryStringBuilder.append("c.id = ");
queryStringBuilder.append(idParamName);
queryStringBuilder.append(" AND ");
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
queryStringBuilder.append(" )");
if (i < itemIdentities.size() - 1) {
queryStringBuilder.append(" OR ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) {
return partitionKeyDefinition.getPaths()
.stream()
.map(pathPart -> StringUtils.substring(pathPart, 1))
.map(pathPart -> StringUtils.replace(pathPart, "\"", "\\"))
.map(part -> "[\"" + part + "\"]")
.collect(Collectors.joining());
}
private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
DocumentCollection collection,
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) {
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(),
sqlQuery,
rangeQueryMap,
options,
collection.getResourceId(),
parentResourceLink,
activityId,
klass,
resourceTypeEnum);
return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync);
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, String query, CosmosQueryRequestOptions options) {
return queryDocuments(collectionLink, new SqlQuerySpec(query), options);
}
private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return new IDocumentQueryClient () {
@Override
public RxCollectionCache getCollectionCache() {
return RxDocumentClientImpl.this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return RxDocumentClientImpl.this.partitionKeyRangeCache;
}
@Override
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy;
}
@Override
public ConsistencyLevel getDefaultConsistencyLevelAsync() {
return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel();
}
@Override
public ConsistencyLevel getDesiredConsistencyLevelAsync() {
return RxDocumentClientImpl.this.consistencyLevel;
}
@Override
public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) {
if (operationContextAndListenerTuple == null) {
return RxDocumentClientImpl.this.query(request).single();
} else {
final OperationListener listener =
operationContextAndListenerTuple.getOperationListener();
final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext();
request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId());
listener.requestListener(operationContext, request);
return RxDocumentClientImpl.this.query(request).single().doOnNext(
response -> listener.responseListener(operationContext, response)
).doOnError(
ex -> listener.exceptionListener(operationContext, ex)
);
}
}
@Override
public QueryCompatibilityMode getQueryCompatibilityMode() {
return QueryCompatibilityMode.Default;
}
@Override
public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) {
return null;
}
};
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
SqlQuerySpecLogger.getInstance().logQuery(querySpec);
return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document);
}
@Override
public Flux<FeedResponse<Document>> queryDocumentChangeFeed(
final DocumentCollection collection,
final CosmosChangeFeedRequestOptions changeFeedOptions) {
checkNotNull(collection, "Argument 'collection' must not be null.");
ChangeFeedQueryImpl<Document> changeFeedQueryImpl = new ChangeFeedQueryImpl<>(
this,
ResourceType.Document,
Document.class,
collection.getAltLink(),
collection.getResourceId(),
changeFeedOptions);
return changeFeedQueryImpl.executeAsync();
}
@Override
public Flux<FeedResponse<Document>> readAllDocuments(
String collectionLink,
PartitionKey partitionKey,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (partitionKey == null) {
throw new IllegalArgumentException("partitionKey");
}
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null
);
Flux<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request).flux();
return collectionObs.flatMap(documentCollectionResourceResponse -> {
DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
String pkSelector = createPkSelector(pkDefinition);
SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector);
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
final CosmosQueryRequestOptions effectiveOptions =
ModelBridgeInternal.createQueryRequestOptions(options);
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> {
Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache
.tryLookupAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null).flux();
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(partitionKey),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
return createQueryInternal(
resourceLink,
querySpec,
ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()),
Document.class,
ResourceType.Document,
queryClient,
activityId);
});
},
invalidPartitionExceptionRetryPolicy);
});
}
@Override
public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() {
return queryPlanCache;
}
@Override
public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class,
Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT));
}
private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
validateResource(storedProcedure);
String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType,
ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
return request;
}
private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (udf == null) {
throw new IllegalArgumentException("udf");
}
validateResource(udf);
String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Create);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId());
RxDocumentClientImpl.validateResource(storedProcedure);
String path = Utils.joinPath(storedProcedure.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class,
Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
List<Object> procedureParams) {
return this.executeStoredProcedure(storedProcedureLink, null, procedureParams);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy);
}
@Override
public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy);
}
private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) {
try {
logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript);
requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ExecuteJavaScript,
ResourceType.StoredProcedure, path,
procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "",
requestHeaders, options);
if (retryPolicy != null) {
retryPolicy.onBeforeSendRequest(request);
}
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options))
.map(response -> {
this.captureSessionToken(request, response);
return toStoredProcedureResponse(response);
}));
} catch (Exception e) {
logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
DocumentClientRetryPolicy requestRetryPolicy,
boolean disableAutomaticIdGeneration) {
try {
logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size());
Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true));
} catch (Exception ex) {
logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex);
return Mono.error(ex);
}
}
@Override
public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path,
trigger, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId());
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(trigger.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Trigger, Trigger.class,
Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryTriggers(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger);
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (udf == null) {
throw new IllegalArgumentException("udf");
}
logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId());
validateResource(udf);
String path = Utils.joinPath(udf.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class,
Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
String query, CosmosQueryRequestOptions options) {
return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction);
}
@Override
public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Conflict, Conflict.class,
Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryConflicts(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict);
}
@Override
public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (user == null) {
throw new IllegalArgumentException("user");
}
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.User, path, user, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (user == null) {
throw new IllegalArgumentException("user");
}
logger.debug("Replacing a User. user id [{}]", user.getId());
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(user.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.User, path, user, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Deleting a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Reading a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.User, User.class,
Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) {
return queryUsers(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User);
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(clientEncryptionKeyLink)) {
throw new IllegalArgumentException("clientEncryptionKeyLink");
}
logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink);
String path = Utils.joinPath(clientEncryptionKeyLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink,
ClientEncryptionKey clientEncryptionKey, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId());
RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey,
String nameBasedLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey,
nameBasedLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId());
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(nameBasedLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey,
OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders,
options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class,
Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey);
}
@Override
public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy());
}
private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
if (permission == null) {
throw new IllegalArgumentException("permission");
}
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Permission, path, permission, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (permission == null) {
throw new IllegalArgumentException("permission");
}
logger.debug("Replacing a Permission. permission id [{}]", permission.getId());
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(permission.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Reading a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
return readFeed(options, ResourceType.Permission, Permission.class,
Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query,
CosmosQueryRequestOptions options) {
return queryPermissions(userLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission);
}
@Override
public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
if (offer == null) {
throw new IllegalArgumentException("offer");
}
logger.debug("Replacing an Offer. offer id [{}]", offer.getId());
RxDocumentClientImpl.validateResource(offer);
String path = Utils.joinPath(offer.getSelfLink(), null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace,
ResourceType.Offer, path, offer, null, null);
return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Offer>> readOffer(String offerLink) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(offerLink)) {
throw new IllegalArgumentException("offerLink");
}
logger.debug("Reading an Offer. offerLink [{}]", offerLink);
String path = Utils.joinPath(offerLink, null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Offer, Offer.class,
Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null));
}
private <T extends Resource> Flux<FeedResponse<T>> readFeed(CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options);
int maxPageSize = maxItemCount != null ? maxItemCount : -1;
final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options;
DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> {
Map<String, String> requestHeaders = new HashMap<>();
if (continuationToken != null) {
requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken);
}
requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize));
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions);
retryPolicy.onBeforeSendRequest(request);
return request;
};
Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper
.inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)),
retryPolicy);
return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, maxPageSize);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) {
return queryOffers(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer);
}
@Override
public Mono<DatabaseAccount> getDatabaseAccount() {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy),
documentClientRetryPolicy);
}
@Override
public DatabaseAccount getLatestDatabaseAccount() {
return this.globalEndpointManager.getLatestDatabaseAccount();
}
private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Getting Database Account");
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read,
ResourceType.DatabaseAccount, "",
(HashMap<String, String>) null,
null);
return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount);
} catch (Exception e) {
logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Object getSession() {
return this.sessionContainer;
}
public void setSession(Object sessionContainer) {
this.sessionContainer = (SessionContainer) sessionContainer;
}
@Override
public RxClientCollectionCache getCollectionCache() {
return this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return partitionKeyRangeCache;
}
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
return Flux.defer(() -> {
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null);
return this.populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
requestPopulated.setEndpointOverride(endpoint);
return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> {
String message = String.format("Failed to retrieve database account information. %s",
e.getCause() != null
? e.getCause().toString()
: e.toString());
logger.warn(message);
}).map(rsp -> rsp.getResource(DatabaseAccount.class))
.doOnNext(databaseAccount ->
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled()
&& BridgeInternal.isEnableMultipleWriteLocations(databaseAccount));
});
});
}
/**
* Certain requests must be routed through gateway even when the client connectivity mode is direct.
*
* @param request
* @return RxStoreModel
*/
private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) {
if (request.UseGatewayMode) {
return this.gatewayProxy;
}
ResourceType resourceType = request.getResourceType();
OperationType operationType = request.getOperationType();
if (resourceType == ResourceType.Offer ||
resourceType == ResourceType.ClientEncryptionKey ||
resourceType.isScript() && operationType != OperationType.ExecuteJavaScript ||
resourceType == ResourceType.PartitionKeyRange ||
resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) {
return this.gatewayProxy;
}
if (operationType == OperationType.Create
|| operationType == OperationType.Upsert) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection ||
resourceType == ResourceType.Permission) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Delete) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Replace) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Read) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else {
if ((operationType == OperationType.Query ||
operationType == OperationType.SqlQuery ||
operationType == OperationType.ReadFeed) &&
Utils.isCollectionChild(request.getResourceType())) {
if (request.getPartitionKeyRangeIdentity() == null &&
request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) {
return this.gatewayProxy;
}
}
return this.storeModel;
}
}
@Override
public void close() {
logger.info("Attempting to close client {}", this.clientId);
if (!closed.getAndSet(true)) {
activeClientsCnt.decrementAndGet();
logger.info("Shutting down ...");
logger.info("Closing Global Endpoint Manager ...");
LifeCycleUtils.closeQuietly(this.globalEndpointManager);
logger.info("Closing StoreClientFactory ...");
LifeCycleUtils.closeQuietly(this.storeClientFactory);
logger.info("Shutting down reactorHttpClient ...");
LifeCycleUtils.closeQuietly(this.reactorHttpClient);
logger.info("Shutting down CpuMonitor ...");
CpuMemoryMonitor.unregister(this);
if (this.throughputControlEnabled.get()) {
logger.info("Closing ThroughputControlStore ...");
this.throughputControlStore.close();
}
logger.info("Shutting down completed.");
} else {
logger.warn("Already shutdown!");
}
}
@Override
public ItemDeserializer getItemDeserializer() {
return this.itemDeserializer;
}
@Override
public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group can not be null");
if (this.throughputControlEnabled.compareAndSet(false, true)) {
this.throughputControlStore =
new ThroughputControlStore(
this.collectionCache,
this.connectionPolicy.getConnectionMode(),
this.partitionKeyRangeCache);
this.storeModel.enableThroughputControl(throughputControlStore);
}
this.throughputControlStore.enableThroughputControlGroup(group);
}
private static SqlQuerySpec createLogicalPartitionScanQuerySpec(
PartitionKey partitionKey,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE");
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey);
String pkParamName = "@pkValue";
parameters.add(new SqlParameter(pkParamName, pkValue));
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
@Override
public Mono<List<FeedRange>> getFeedRanges(String collectionLink) {
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
collectionLink,
new HashMap<>());
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null);
invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request);
return ObservableHelper.inlineIfPossibleAsObs(
() -> getFeedRangesInternal(request, collectionLink),
invalidPartitionExceptionRetryPolicy);
}
private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) {
logger.debug("getFeedRange collectionLink=[{}]", collectionLink);
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null,
request);
return collectionObs.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache
.tryGetOverlappingRangesAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null);
return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request));
});
}
private static List<FeedRange> toFeedRanges(
Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) {
final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v;
if (partitionKeyRangeList == null) {
request.forceNameCacheRefresh = true;
throw new InvalidPartitionException();
}
List<FeedRange> feedRanges = new ArrayList<>();
partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange)));
return feedRanges;
}
private static FeedRange toFeedRange(PartitionKeyRange pkRange) {
return new FeedRangeEpkImpl(pkRange.toRange());
}
} |
that's no different from async version. Should `createHttpRequestBase` -> `protected createHttpRequest` in the base class ? | public HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException {
return createHttpRequestBase(methodParser, serializer, false, args);
} | } | public HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException {
return createHttpRequest(methodParser, serializer, false, args);
} | class SyncRestProxy extends RestProxyBase {
/**
* Create a RestProxy.
*
* @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests.
* @param serializer the serializer that will be used to convert response bodies to POJOs.
* @param interfaceParser the parser that contains information about the interface describing REST API methods that
*/
public SyncRestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) {
super(httpPipeline, serializer, interfaceParser);
}
/**
* Send the provided request asynchronously, applying any request policies provided to the HttpClient instance.
*
* @param request the HTTP request to send
* @param contextData the context
* @return a {@link Mono} that emits HttpResponse asynchronously
*/
public HttpResponse send(HttpRequest request, Context contextData) {
return httpPipeline.sendSync(request, contextData);
}
@Override
public Object invoke(Object proxy, Method method, RequestOptions options, EnumSet<ErrorOptions> errorOptions, Consumer<HttpRequest> requestCallback, SwaggerMethodParser methodParser, HttpRequest request, Context context) {
HttpResponseDecoder.HttpDecodedResponse decodedResponse = null;
Throwable throwable = null;
try {
context = startTracingSpan(method, context);
if (options != null && requestCallback != null) {
requestCallback.accept(request);
}
if (request.getBodyAsBinaryData() != null) {
request.setBody(RestProxyUtils.validateLengthSync(request));
}
final HttpResponse response = send(request, context);
decodedResponse = this.decoder.decodeSync(response, methodParser);
return handleRestReturnType(decodedResponse, methodParser, methodParser.getReturnType(), context, options, errorOptions);
} catch (RuntimeException e) {
throwable = e;
throw LOGGER.logExceptionAsError(e);
} finally {
if (decodedResponse != null || throwable != null) {
endTracingSpan(decodedResponse, throwable, context);
}
}
}
/**
* Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing
* additional context information.
*
* @param method Service method being called.
* @param context Context information about the current service call.
* @return The updated context containing the span context.
*/
private Context startTracingSpan(Method method, Context context) {
if (!TracerProxy.isTracingEnabled()) {
return context;
}
if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) {
return context;
}
String spanName = interfaceParser.getServiceName() + "." + method.getName();
context = TracerProxy.setSpanName(spanName, context);
return TracerProxy.start(spanName, context);
}
/**
* Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status
* code' OR (2) emits provided response if it's status code ia allowed.
*
* 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[]
* of additional allowed status codes.
*
* @param decodedResponse The HttpResponse to check.
* @param methodParser The method parser that contains information about the service interface method that initiated
* the HTTP request.
* @return An async-version of the provided decodedResponse.
*/
private HttpResponseDecoder.HttpDecodedResponse ensureExpectedStatus(final HttpResponseDecoder.HttpDecodedResponse decodedResponse,
final SwaggerMethodParser methodParser, RequestOptions options, EnumSet<ErrorOptions> errorOptions) {
final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode();
if (methodParser.isExpectedResponseStatusCode(responseStatusCode)
|| (options != null && errorOptions.contains(ErrorOptions.NO_THROW))) {
return decodedResponse;
}
Exception e;
BinaryData responseData = decodedResponse.getSourceResponse().getBodyAsBinaryData();
byte[] responseBytes = responseData == null ? null : responseData.toBytes();
if (responseBytes == null || responseBytes.length == 0) {
e = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode),
decodedResponse.getSourceResponse(), null, null);
} else {
Object decodedBody = decodedResponse.getDecodedBodySync(responseBytes);
e = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode),
decodedResponse.getSourceResponse(), responseBytes, decodedBody);
}
if (e instanceof RuntimeException) {
throw LOGGER.logExceptionAsError((RuntimeException) e);
} else {
throw LOGGER.logExceptionAsError(new RuntimeException(e));
}
}
private Object handleRestResponseReturnType(final HttpResponseDecoder.HttpDecodedResponse response,
final SwaggerMethodParser methodParser,
final Type entityType) {
if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) {
if (entityType.equals(StreamResponse.class)) {
return createResponse(response, entityType, null);
}
final Type bodyType = TypeUtil.getRestResponseBodyType(entityType);
if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) {
response.getSourceResponse().close();
return createResponse(response, entityType, null);
} else {
Object bodyAsObject = handleBodyReturnType(response, methodParser, bodyType);
Response<?> httpResponse = createResponse(response, entityType, bodyAsObject);
if (httpResponse == null) {
return createResponse(response, entityType, null);
}
return httpResponse;
}
} else {
return handleBodyReturnType(response, methodParser, entityType);
}
}
private Object handleBodyReturnType(final HttpResponseDecoder.HttpDecodedResponse response,
final SwaggerMethodParser methodParser, final Type entityType) {
final int responseStatusCode = response.getSourceResponse().getStatusCode();
final HttpMethod httpMethod = methodParser.getHttpMethod();
final Type returnValueWireType = methodParser.getReturnValueWireType();
final Object result;
if (httpMethod == HttpMethod.HEAD
&& (TypeUtil.isTypeOrSubTypeOf(
entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) {
boolean isSuccess = (responseStatusCode / 100) == 2;
result = isSuccess;
} else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) {
byte[] responseBodyBytes = response.getSourceResponse().getBodyAsBinaryData().toBytes();
if (returnValueWireType == Base64Url.class) {
responseBodyBytes = new Base64Url(responseBodyBytes).decodedBytes();
}
result = responseBodyBytes;
} else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) {
result = response.getSourceResponse().getBodyAsBinaryData();
} else {
result = response.getDecodedBodySync((byte[]) null);
}
return result;
}
/**
* Handle the provided asynchronous HTTP response and return the deserialized value.
*
* @param httpDecodedResponse the asynchronous HTTP response to the original HTTP request
* @param methodParser the SwaggerMethodParser that the request originates from
* @param returnType the type of value that will be returned
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return the deserialized result
*/
private Object handleRestReturnType(final HttpResponseDecoder.HttpDecodedResponse httpDecodedResponse,
final SwaggerMethodParser methodParser,
final Type returnType,
final Context context,
final RequestOptions options,
EnumSet<ErrorOptions> errorOptions) {
final HttpResponseDecoder.HttpDecodedResponse expectedResponse =
ensureExpectedStatus(httpDecodedResponse, methodParser, options, errorOptions);
final Object result;
if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType,
Void.class)) {
result = expectedResponse;
} else {
result = handleRestResponseReturnType(httpDecodedResponse, methodParser, returnType);
}
return result;
}
private static void endTracingSpan(HttpResponseDecoder.HttpDecodedResponse httpDecodedResponse, Throwable throwable, Context tracingContext) {
if (tracingContext == null) {
return;
}
Object disableTracingValue = (tracingContext.getData(Tracer.DISABLE_TRACING_KEY).isPresent()
? tracingContext.getData(Tracer.DISABLE_TRACING_KEY).get() : null);
boolean disableTracing = Boolean.TRUE.equals(disableTracingValue != null ? disableTracingValue : false);
if (disableTracing) {
return;
}
int statusCode = 0;
if (httpDecodedResponse != null) {
statusCode = httpDecodedResponse.getSourceResponse().getStatusCode();
} else if (throwable != null) {
if (throwable instanceof HttpResponseException) {
HttpResponseException exception = (HttpResponseException) throwable;
statusCode = exception.getResponse().getStatusCode();
}
}
TracerProxy.end(statusCode, throwable, tracingContext);
}
public void updateRequest(RequestDataConfiguration requestDataConfiguration, SerializerAdapter serializerAdapter) throws IOException {
boolean isJson = requestDataConfiguration.isJson();
HttpRequest request = requestDataConfiguration.getHttpRequest();
Object bodyContentObject = requestDataConfiguration.getBodyContent();
if (isJson) {
ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream();
serializerAdapter.serialize(bodyContentObject, SerializerEncoding.JSON, stream);
request.setHeader("Content-Length", String.valueOf(stream.size()));
request.setBody(BinaryData.fromStream(new ByteArrayInputStream(stream.toByteArray(), 0, stream.size())));
} else if (bodyContentObject instanceof byte[]) {
request.setBody((byte[]) bodyContentObject);
} else if (bodyContentObject instanceof String) {
final String bodyContentString = (String) bodyContentObject;
if (!bodyContentString.isEmpty()) {
request.setBody(bodyContentString);
}
} else if (bodyContentObject instanceof ByteBuffer) {
request.setBody(((ByteBuffer) bodyContentObject).array());
} else {
ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream();
serializerAdapter.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream);
request.setHeader("Content-Length", String.valueOf(stream.size()));
request.setBody(stream.toByteArray());
}
}
} | class SyncRestProxy extends RestProxyBase {
/**
* Create a RestProxy.
*
* @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests.
* @param serializer the serializer that will be used to convert response bodies to POJOs.
* @param interfaceParser the parser that contains information about the interface describing REST API methods that
*/
public SyncRestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) {
super(httpPipeline, serializer, interfaceParser);
}
/**
* Send the provided request asynchronously, applying any request policies provided to the HttpClient instance.
*
* @param request the HTTP request to send
* @param contextData the context
* @return a {@link Mono} that emits HttpResponse asynchronously
*/
HttpResponse send(HttpRequest request, Context contextData) {
return httpPipeline.sendSync(request, contextData);
}
@Override
public Object invoke(Object proxy, Method method, RequestOptions options, EnumSet<ErrorOptions> errorOptions, Consumer<HttpRequest> requestCallback, SwaggerMethodParser methodParser, HttpRequest request, Context context) {
HttpResponseDecoder.HttpDecodedResponse decodedResponse = null;
Throwable throwable = null;
try {
context = startTracingSpan(method, context);
if (options != null && requestCallback != null) {
requestCallback.accept(request);
}
if (request.getBodyAsBinaryData() != null) {
request.setBody(RestProxyUtils.validateLengthSync(request));
}
final HttpResponse response = send(request, context);
decodedResponse = this.decoder.decodeSync(response, methodParser);
return handleRestReturnType(decodedResponse, methodParser, methodParser.getReturnType(), context, options, errorOptions);
} catch (RuntimeException e) {
throwable = e;
throw LOGGER.logExceptionAsError(e);
} finally {
if (decodedResponse != null || throwable != null) {
endTracingSpan(decodedResponse, throwable, context);
}
}
}
/**
* Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status
* code' OR (2) emits provided response if it's status code ia allowed.
*
* 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[]
* of additional allowed status codes.
*
* @param decodedResponse The HttpResponse to check.
* @param methodParser The method parser that contains information about the service interface method that initiated
* the HTTP request.
* @return An async-version of the provided decodedResponse.
*/
private HttpResponseDecoder.HttpDecodedResponse ensureExpectedStatus(final HttpResponseDecoder.HttpDecodedResponse decodedResponse,
final SwaggerMethodParser methodParser, RequestOptions options, EnumSet<ErrorOptions> errorOptions) {
final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode();
if (methodParser.isExpectedResponseStatusCode(responseStatusCode)
|| (options != null && errorOptions.contains(ErrorOptions.NO_THROW))) {
return decodedResponse;
}
Exception e;
BinaryData responseData = decodedResponse.getSourceResponse().getBodyAsBinaryData();
byte[] responseBytes = responseData == null ? null : responseData.toBytes();
if (responseBytes == null || responseBytes.length == 0) {
e = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode),
decodedResponse.getSourceResponse(), null, null);
} else {
Object decodedBody = decodedResponse.getDecodedBodySync(responseBytes);
e = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode),
decodedResponse.getSourceResponse(), responseBytes, decodedBody);
}
if (e instanceof RuntimeException) {
throw LOGGER.logExceptionAsError((RuntimeException) e);
} else {
throw LOGGER.logExceptionAsError(new RuntimeException(e));
}
}
private Object handleRestResponseReturnType(final HttpResponseDecoder.HttpDecodedResponse response,
final SwaggerMethodParser methodParser,
final Type entityType) {
if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) {
if (entityType.equals(StreamResponse.class)) {
return createResponse(response, entityType, null);
}
final Type bodyType = TypeUtil.getRestResponseBodyType(entityType);
if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) {
response.getSourceResponse().close();
return createResponse(response, entityType, null);
} else {
Object bodyAsObject = handleBodyReturnType(response, methodParser, bodyType);
Response<?> httpResponse = createResponse(response, entityType, bodyAsObject);
if (httpResponse == null) {
return createResponse(response, entityType, null);
}
return httpResponse;
}
} else {
return handleBodyReturnType(response, methodParser, entityType);
}
}
private Object handleBodyReturnType(final HttpResponseDecoder.HttpDecodedResponse response,
final SwaggerMethodParser methodParser, final Type entityType) {
final int responseStatusCode = response.getSourceResponse().getStatusCode();
final HttpMethod httpMethod = methodParser.getHttpMethod();
final Type returnValueWireType = methodParser.getReturnValueWireType();
final Object result;
if (httpMethod == HttpMethod.HEAD
&& (TypeUtil.isTypeOrSubTypeOf(
entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) {
boolean isSuccess = (responseStatusCode / 100) == 2;
result = isSuccess;
} else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) {
BinaryData binaryData = response.getSourceResponse().getBodyAsBinaryData();
byte[] responseBodyBytes = binaryData != null ? binaryData.toBytes() : null;
if (returnValueWireType == Base64Url.class) {
responseBodyBytes = new Base64Url(responseBodyBytes).decodedBytes();
}
result = responseBodyBytes != null ? (responseBodyBytes.length == 0 ? null : responseBodyBytes) : null;
} else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) {
result = response.getSourceResponse().getBodyAsBinaryData();
} else {
result = response.getDecodedBodySync((byte[]) null);
}
return result;
}
/**
* Handle the provided asynchronous HTTP response and return the deserialized value.
*
* @param httpDecodedResponse the asynchronous HTTP response to the original HTTP request
* @param methodParser the SwaggerMethodParser that the request originates from
* @param returnType the type of value that will be returned
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return the deserialized result
*/
private Object handleRestReturnType(final HttpResponseDecoder.HttpDecodedResponse httpDecodedResponse,
final SwaggerMethodParser methodParser,
final Type returnType,
final Context context,
final RequestOptions options,
EnumSet<ErrorOptions> errorOptions) {
final HttpResponseDecoder.HttpDecodedResponse expectedResponse =
ensureExpectedStatus(httpDecodedResponse, methodParser, options, errorOptions);
final Object result;
if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType,
Void.class)) {
result = expectedResponse;
} else {
result = handleRestResponseReturnType(httpDecodedResponse, methodParser, returnType);
}
return result;
}
public void updateRequest(RequestDataConfiguration requestDataConfiguration, SerializerAdapter serializerAdapter) throws IOException {
boolean isJson = requestDataConfiguration.isJson();
HttpRequest request = requestDataConfiguration.getHttpRequest();
Object bodyContentObject = requestDataConfiguration.getBodyContent();
if (isJson) {
byte[] serializedBytes = serializerAdapter.serializeToBytes(bodyContentObject, SerializerEncoding.JSON);
ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream();
serializerAdapter.serialize(bodyContentObject, SerializerEncoding.JSON, stream);
request.setHeader("Content-Length", String.valueOf(serializedBytes.length));
request.setBody(BinaryData.fromBytes(serializedBytes));
} else if (bodyContentObject instanceof byte[]) {
request.setBody((byte[]) bodyContentObject);
} else if (bodyContentObject instanceof String) {
final String bodyContentString = (String) bodyContentObject;
if (!bodyContentString.isEmpty()) {
request.setBody(bodyContentString);
}
} else if (bodyContentObject instanceof ByteBuffer) {
if (((ByteBuffer) bodyContentObject).hasArray()) {
request.setBody(((ByteBuffer) bodyContentObject).array());
} else {
byte[] array = new byte[((ByteBuffer) bodyContentObject).remaining()];
((ByteBuffer) bodyContentObject).get(array);
request.setBody(array);
}
} else {
byte[] serializedBytes = serializerAdapter
.serializeToBytes(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()));
request.setHeader("Content-Length", String.valueOf(serializedBytes.length));
request.setBody(serializedBytes);
}
}
} |
just a generic question: should we retry few times here in case any transient issue> | private void loadAzureVmMetaData() {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null) {
this.populateAzureVmMetaData(metadataSnapshot);
return;
}
URI targetEndpoint = null;
try {
targetEndpoint = new URI(AZURE_VM_METADATA);
} catch (URISyntaxException ex) {
logger.info("Unable to parse azure vm metadata url");
return;
}
HashMap<String, String> headers = new HashMap<>();
headers.put("Metadata", "true");
HttpHeaders httpHeaders = new HttpHeaders(headers);
HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(),
httpHeaders);
Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest);
httpResponseMono
.flatMap(response -> response.bodyAsString()).map(metadataJson -> parse(metadataJson,
AzureVMMetadata.class)).doOnSuccess(metadata -> {
azureVmMetaDataSingleton.compareAndSet(null, metadata);
this.populateAzureVmMetaData(metadata);
}).onErrorResume(throwable -> {
logger.info("Client is not on azure vm");
logger.debug("Unable to get azure vm metadata", throwable);
return Mono.empty();
}).subscribe();
} | }).onErrorResume(throwable -> { | private void loadAzureVmMetaData() {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null) {
this.populateAzureVmMetaData(metadataSnapshot);
return;
}
URI targetEndpoint = null;
try {
targetEndpoint = new URI(AZURE_VM_METADATA);
} catch (URISyntaxException ex) {
logger.info("Unable to parse azure vm metadata url");
return;
}
HashMap<String, String> headers = new HashMap<>();
headers.put("Metadata", "true");
HttpHeaders httpHeaders = new HttpHeaders(headers);
HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(),
httpHeaders);
Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest);
httpResponseMono
.flatMap(response -> response.bodyAsString()).map(metadataJson -> parse(metadataJson,
AzureVMMetadata.class)).doOnSuccess(metadata -> {
azureVmMetaDataSingleton.compareAndSet(null, metadata);
this.populateAzureVmMetaData(metadata);
}).onErrorResume(throwable -> {
logger.info("Client is not on azure vm");
logger.debug("Unable to get azure vm metadata", throwable);
return Mono.empty();
}).subscribe();
} | class ClientTelemetry {
public final static int ONE_KB_TO_BYTES = 1024;
public final static int REQUEST_LATENCY_MAX_MILLI_SEC = 300000;
public final static int REQUEST_LATENCY_SUCCESS_PRECISION = 4;
public final static int REQUEST_LATENCY_FAILURE_PRECISION = 2;
public final static String REQUEST_LATENCY_NAME = "RequestLatency";
public final static String REQUEST_LATENCY_UNIT = "MilliSecond";
public final static int REQUEST_CHARGE_MAX = 10000;
public final static int REQUEST_CHARGE_PRECISION = 2;
public final static String REQUEST_CHARGE_NAME = "RequestCharge";
public final static String REQUEST_CHARGE_UNIT = "RU";
public final static String TCP_NEW_CHANNEL_LATENCY_NAME = "TcpNewChannelOpenLatency";
public final static String TCP_NEW_CHANNEL_LATENCY_UNIT = "MilliSecond";
public final static int TCP_NEW_CHANNEL_LATENCY_MAX_MILLI_SEC = 300000;
public final static int TCP_NEW_CHANNEL_LATENCY_PRECISION = 2;
public final static int CPU_MAX = 100;
public final static int CPU_PRECISION = 2;
private final static String CPU_NAME = "CPU";
private final static String CPU_UNIT = "Percentage";
public final static int MEMORY_MAX_IN_MB = 102400;
public final static int MEMORY_PRECISION = 2;
private final static String MEMORY_NAME = "MemoryRemaining";
private final static String MEMORY_UNIT = "MB";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final static AtomicLong instanceCount = new AtomicLong(0);
private final static AtomicReference<AzureVMMetadata> azureVmMetaDataSingleton =
new AtomicReference<>(null);
private ClientTelemetryInfo clientTelemetryInfo;
private final HttpClient httpClient;
private final ScheduledThreadPoolExecutor scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
new CosmosDaemonThreadFactory("ClientTelemetry-" + instanceCount.incrementAndGet()));
private final Scheduler scheduler = Schedulers.fromExecutor(scheduledExecutorService);
private static final Logger logger = LoggerFactory.getLogger(ClientTelemetry.class);
private volatile boolean isClosed;
private volatile boolean isClientTelemetryEnabled;
private static String AZURE_VM_METADATA = "http:
private static final double PERCENTILE_50 = 50.0;
private static final double PERCENTILE_90 = 90.0;
private static final double PERCENTILE_95 = 95.0;
private static final double PERCENTILE_99 = 99.0;
private static final double PERCENTILE_999 = 99.9;
private final int clientTelemetrySchedulingSec;
private final IAuthorizationTokenProvider tokenProvider;
private final String globalDatabaseAccountName;
public ClientTelemetry(DiagnosticsClientContext diagnosticsClientContext,
Boolean acceleratedNetworking,
String clientId,
String processId,
String userAgent,
ConnectionMode connectionMode,
String globalDatabaseAccountName,
String applicationRegion,
String hostEnvInfo,
HttpClient httpClient,
boolean isClientTelemetryEnabled,
IAuthorizationTokenProvider tokenProvider,
List<String> preferredRegions
) {
clientTelemetryInfo = new ClientTelemetryInfo(
getMachineId(diagnosticsClientContext),
clientId,
processId,
userAgent,
connectionMode,
globalDatabaseAccountName,
applicationRegion,
hostEnvInfo,
acceleratedNetworking,
preferredRegions);
this.isClosed = false;
this.httpClient = httpClient;
this.isClientTelemetryEnabled = isClientTelemetryEnabled;
this.clientTelemetrySchedulingSec = Configs.getClientTelemetrySchedulingInSec();
this.tokenProvider = tokenProvider;
this.globalDatabaseAccountName = globalDatabaseAccountName;
}
public ClientTelemetryInfo getClientTelemetryInfo() {
return clientTelemetryInfo;
}
public static String getMachineId(DiagnosticsClientContext diagnosticsClientContext) {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null && metadataSnapshot.getVmId() != null) {
String machineId = "vmId:" + metadataSnapshot.getVmId();
if (diagnosticsClientContext != null) {
diagnosticsClientContext.getConfig().withMachineId(machineId);
}
return machineId;
}
if (diagnosticsClientContext == null) {
return "";
}
return diagnosticsClientContext.getConfig().getMachineId();
}
public static void recordValue(ConcurrentDoubleHistogram doubleHistogram, long value) {
try {
doubleHistogram.recordValue(value);
} catch (Exception ex) {
logger.warn("Error while recording value for client telemetry. ", ex);
}
}
public static void recordValue(ConcurrentDoubleHistogram doubleHistogram, double value) {
try {
doubleHistogram.recordValue(value);
} catch (Exception ex) {
logger.warn("Error while recording value for client telemetry. ", ex);
}
}
public boolean isClientTelemetryEnabled() {
return isClientTelemetryEnabled;
}
public void init() {
loadAzureVmMetaData();
sendClientTelemetry().subscribe();
}
public void close() {
this.isClosed = true;
this.scheduledExecutorService.shutdown();
logger.debug("GlobalEndpointManager closed.");
}
private Mono<Void> sendClientTelemetry() {
return Mono.delay(Duration.ofSeconds(clientTelemetrySchedulingSec), CosmosSchedulers.COSMOS_PARALLEL)
.flatMap(t -> {
if (this.isClosed) {
logger.warn("client already closed");
return Mono.empty();
}
if (!Configs.isClientTelemetryEnabled(this.isClientTelemetryEnabled)) {
logger.trace("client telemetry not enabled");
return Mono.empty();
}
readHistogram();
try {
String endpoint = Configs.getClientTelemetryEndpoint();
if (StringUtils.isEmpty(endpoint)) {
logger.info("ClientTelemetry {}",
OBJECT_MAPPER.writeValueAsString(this.clientTelemetryInfo));
clearDataForNextRun();
return this.sendClientTelemetry();
} else {
URI targetEndpoint = new URI(endpoint);
ByteBuffer byteBuffer =
BridgeInternal.serializeJsonToByteBuffer(this.clientTelemetryInfo,
ClientTelemetry.OBJECT_MAPPER);
Flux<byte[]> fluxBytes = Flux.just(RxDocumentServiceRequest.toByteArray(byteBuffer));
Map<String, String> headers = new HashMap<>();
String date = Utils.nowAsRFC1123();
headers.put(HttpConstants.HttpHeaders.X_DATE, date);
String authorization = this.tokenProvider.getUserAuthorizationToken(
"", ResourceType.ClientTelemetry, RequestVerb.POST, headers,
AuthorizationTokenType.PrimaryMasterKey, null);
try {
authorization = URLEncoder.encode(authorization, Constants.UrlEncodingInfo.UTF_8);
} catch (UnsupportedEncodingException e) {
logger.error("Failed to encode authToken. Exception: ", e);
this.clearDataForNextRun();
return this.sendClientTelemetry();
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
httpHeaders.set(HttpConstants.HttpHeaders.CONTENT_ENCODING, RuntimeConstants.Encoding.GZIP);
httpHeaders.set(HttpConstants.HttpHeaders.X_DATE, date);
httpHeaders.set(HttpConstants.HttpHeaders.DATABASE_ACCOUNT_NAME,
this.globalDatabaseAccountName);
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
String envName = Configs.getEnvironmentName();
if (StringUtils.isNotEmpty(envName)) {
httpHeaders.set(HttpConstants.HttpHeaders.ENVIRONMENT_NAME, envName);
}
HttpRequest httpRequest = new HttpRequest(HttpMethod.POST, targetEndpoint,
targetEndpoint.getPort(), httpHeaders, fluxBytes);
Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest,
Duration.ofSeconds(Configs.getHttpResponseTimeoutInSeconds()));
return httpResponseMono.flatMap(response -> {
if (response.statusCode() != HttpConstants.StatusCodes.OK) {
logger.error("Client telemetry request did not succeeded, status code {}",
response.statusCode());
}
this.clearDataForNextRun();
return this.sendClientTelemetry();
}).onErrorResume(throwable -> {
logger.error("Error while sending client telemetry request Exception: ", throwable);
this.clearDataForNextRun();
return this.sendClientTelemetry();
});
}
} catch (JsonProcessingException | URISyntaxException ex) {
logger.error("Error while preparing client telemetry. Exception: ", ex);
this.clearDataForNextRun();
return this.sendClientTelemetry();
}
}).onErrorResume(ex -> {
logger.error("sendClientTelemetry() - Unable to send client telemetry" +
". Exception: ", ex);
clearDataForNextRun();
return this.sendClientTelemetry();
}).subscribeOn(scheduler);
}
private void populateAzureVmMetaData(AzureVMMetadata azureVMMetadata) {
this.clientTelemetryInfo.setApplicationRegion(azureVMMetadata.getLocation());
this.clientTelemetryInfo.setMachineId("vmId:" + azureVMMetadata.getVmId());
this.clientTelemetryInfo.setHostEnvInfo(azureVMMetadata.getOsType() + "|" + azureVMMetadata.getSku() +
"|" + azureVMMetadata.getVmSize() + "|" + azureVMMetadata.getAzEnvironment());
}
private static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) {
try {
return OBJECT_MAPPER.readValue(itemResponseBodyAsString, itemClassType);
} catch (IOException e) {
throw new IllegalStateException(
"Failed to parse string [" + itemResponseBodyAsString + "] to POJO.", e);
}
}
private void clearDataForNextRun() {
this.clientTelemetryInfo.getSystemInfoMap().clear();
this.clientTelemetryInfo.getOperationInfoMap().clear();
this.clientTelemetryInfo.getCacheRefreshInfoMap().clear();
for (ConcurrentDoubleHistogram histogram : this.clientTelemetryInfo.getSystemInfoMap().values()) {
histogram.reset();
}
}
private void readHistogram() {
ConcurrentDoubleHistogram cpuHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.CPU_MAX,
ClientTelemetry.CPU_PRECISION);
cpuHistogram.setAutoResize(true);
for (double val : CpuMemoryMonitor.getClientTelemetryCpuLatestList()) {
recordValue(cpuHistogram, val);
}
ReportPayload cpuReportPayload = new ReportPayload(CPU_NAME, CPU_UNIT);
clientTelemetryInfo.getSystemInfoMap().put(cpuReportPayload, cpuHistogram);
ConcurrentDoubleHistogram memoryHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.MEMORY_MAX_IN_MB,
ClientTelemetry.MEMORY_PRECISION);
memoryHistogram.setAutoResize(true);
for (double val : CpuMemoryMonitor.getClientTelemetryMemoryLatestList()) {
recordValue(memoryHistogram, val);
}
ReportPayload memoryReportPayload = new ReportPayload(MEMORY_NAME, MEMORY_UNIT);
clientTelemetryInfo.getSystemInfoMap().put(memoryReportPayload, memoryHistogram);
this.clientTelemetryInfo.setTimeStamp(Instant.now().toString());
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getSystemInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getCacheRefreshInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getOperationInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
}
private void fillMetricsInfo(ReportPayload payload, ConcurrentDoubleHistogram histogram) {
DoubleHistogram copyHistogram = histogram.copy();
payload.getMetricInfo().setCount(copyHistogram.getTotalCount());
payload.getMetricInfo().setMax(copyHistogram.getMaxValue());
payload.getMetricInfo().setMin(copyHistogram.getMinValue());
payload.getMetricInfo().setMean(copyHistogram.getMean());
Map<Double, Double> percentile = new HashMap<>();
percentile.put(PERCENTILE_50, copyHistogram.getValueAtPercentile(PERCENTILE_50));
percentile.put(PERCENTILE_90, copyHistogram.getValueAtPercentile(PERCENTILE_90));
percentile.put(PERCENTILE_95, copyHistogram.getValueAtPercentile(PERCENTILE_95));
percentile.put(PERCENTILE_99, copyHistogram.getValueAtPercentile(PERCENTILE_99));
percentile.put(PERCENTILE_999, copyHistogram.getValueAtPercentile(PERCENTILE_999));
payload.getMetricInfo().setPercentiles(percentile);
}
} | class ClientTelemetry {
public final static int ONE_KB_TO_BYTES = 1024;
public final static int REQUEST_LATENCY_MAX_MILLI_SEC = 300000;
public final static int REQUEST_LATENCY_SUCCESS_PRECISION = 4;
public final static int REQUEST_LATENCY_FAILURE_PRECISION = 2;
public final static String REQUEST_LATENCY_NAME = "RequestLatency";
public final static String REQUEST_LATENCY_UNIT = "MilliSecond";
public final static int REQUEST_CHARGE_MAX = 10000;
public final static int REQUEST_CHARGE_PRECISION = 2;
public final static String REQUEST_CHARGE_NAME = "RequestCharge";
public final static String REQUEST_CHARGE_UNIT = "RU";
public final static String TCP_NEW_CHANNEL_LATENCY_NAME = "TcpNewChannelOpenLatency";
public final static String TCP_NEW_CHANNEL_LATENCY_UNIT = "MilliSecond";
public final static int TCP_NEW_CHANNEL_LATENCY_MAX_MILLI_SEC = 300000;
public final static int TCP_NEW_CHANNEL_LATENCY_PRECISION = 2;
public final static int CPU_MAX = 100;
public final static int CPU_PRECISION = 2;
private final static String CPU_NAME = "CPU";
private final static String CPU_UNIT = "Percentage";
public final static int MEMORY_MAX_IN_MB = 102400;
public final static int MEMORY_PRECISION = 2;
private final static String MEMORY_NAME = "MemoryRemaining";
private final static String MEMORY_UNIT = "MB";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final static AtomicLong instanceCount = new AtomicLong(0);
private final static AtomicReference<AzureVMMetadata> azureVmMetaDataSingleton =
new AtomicReference<>(null);
private ClientTelemetryInfo clientTelemetryInfo;
private final HttpClient httpClient;
private final ScheduledThreadPoolExecutor scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
new CosmosDaemonThreadFactory("ClientTelemetry-" + instanceCount.incrementAndGet()));
private final Scheduler scheduler = Schedulers.fromExecutor(scheduledExecutorService);
private static final Logger logger = LoggerFactory.getLogger(ClientTelemetry.class);
private volatile boolean isClosed;
private volatile boolean isClientTelemetryEnabled;
private static String AZURE_VM_METADATA = "http:
private static final double PERCENTILE_50 = 50.0;
private static final double PERCENTILE_90 = 90.0;
private static final double PERCENTILE_95 = 95.0;
private static final double PERCENTILE_99 = 99.0;
private static final double PERCENTILE_999 = 99.9;
private final int clientTelemetrySchedulingSec;
private final IAuthorizationTokenProvider tokenProvider;
private final String globalDatabaseAccountName;
public ClientTelemetry(DiagnosticsClientContext diagnosticsClientContext,
Boolean acceleratedNetworking,
String clientId,
String processId,
String userAgent,
ConnectionMode connectionMode,
String globalDatabaseAccountName,
String applicationRegion,
String hostEnvInfo,
HttpClient httpClient,
boolean isClientTelemetryEnabled,
IAuthorizationTokenProvider tokenProvider,
List<String> preferredRegions
) {
clientTelemetryInfo = new ClientTelemetryInfo(
getMachineId(diagnosticsClientContext),
clientId,
processId,
userAgent,
connectionMode,
globalDatabaseAccountName,
applicationRegion,
hostEnvInfo,
acceleratedNetworking,
preferredRegions);
this.isClosed = false;
this.httpClient = httpClient;
this.isClientTelemetryEnabled = isClientTelemetryEnabled;
this.clientTelemetrySchedulingSec = Configs.getClientTelemetrySchedulingInSec();
this.tokenProvider = tokenProvider;
this.globalDatabaseAccountName = globalDatabaseAccountName;
}
public ClientTelemetryInfo getClientTelemetryInfo() {
return clientTelemetryInfo;
}
public static String getMachineId(DiagnosticsClientContext diagnosticsClientContext) {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null && metadataSnapshot.getVmId() != null) {
String machineId = "vmId:" + metadataSnapshot.getVmId();
if (diagnosticsClientContext != null) {
diagnosticsClientContext.getConfig().withMachineId(machineId);
}
return machineId;
}
if (diagnosticsClientContext == null) {
return "";
}
return diagnosticsClientContext.getConfig().getMachineId();
}
public static void recordValue(ConcurrentDoubleHistogram doubleHistogram, long value) {
try {
doubleHistogram.recordValue(value);
} catch (Exception ex) {
logger.warn("Error while recording value for client telemetry. ", ex);
}
}
public static void recordValue(ConcurrentDoubleHistogram doubleHistogram, double value) {
try {
doubleHistogram.recordValue(value);
} catch (Exception ex) {
logger.warn("Error while recording value for client telemetry. ", ex);
}
}
public boolean isClientTelemetryEnabled() {
return isClientTelemetryEnabled;
}
public void init() {
loadAzureVmMetaData();
sendClientTelemetry().subscribe();
}
public void close() {
this.isClosed = true;
this.scheduledExecutorService.shutdown();
logger.debug("GlobalEndpointManager closed.");
}
private Mono<Void> sendClientTelemetry() {
return Mono.delay(Duration.ofSeconds(clientTelemetrySchedulingSec), CosmosSchedulers.COSMOS_PARALLEL)
.flatMap(t -> {
if (this.isClosed) {
logger.warn("client already closed");
return Mono.empty();
}
if (!Configs.isClientTelemetryEnabled(this.isClientTelemetryEnabled)) {
logger.trace("client telemetry not enabled");
return Mono.empty();
}
readHistogram();
try {
String endpoint = Configs.getClientTelemetryEndpoint();
if (StringUtils.isEmpty(endpoint)) {
logger.info("ClientTelemetry {}",
OBJECT_MAPPER.writeValueAsString(this.clientTelemetryInfo));
clearDataForNextRun();
return this.sendClientTelemetry();
} else {
URI targetEndpoint = new URI(endpoint);
ByteBuffer byteBuffer =
BridgeInternal.serializeJsonToByteBuffer(this.clientTelemetryInfo,
ClientTelemetry.OBJECT_MAPPER);
Flux<byte[]> fluxBytes = Flux.just(RxDocumentServiceRequest.toByteArray(byteBuffer));
Map<String, String> headers = new HashMap<>();
String date = Utils.nowAsRFC1123();
headers.put(HttpConstants.HttpHeaders.X_DATE, date);
String authorization = this.tokenProvider.getUserAuthorizationToken(
"", ResourceType.ClientTelemetry, RequestVerb.POST, headers,
AuthorizationTokenType.PrimaryMasterKey, null);
try {
authorization = URLEncoder.encode(authorization, Constants.UrlEncodingInfo.UTF_8);
} catch (UnsupportedEncodingException e) {
logger.error("Failed to encode authToken. Exception: ", e);
this.clearDataForNextRun();
return this.sendClientTelemetry();
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
httpHeaders.set(HttpConstants.HttpHeaders.CONTENT_ENCODING, RuntimeConstants.Encoding.GZIP);
httpHeaders.set(HttpConstants.HttpHeaders.X_DATE, date);
httpHeaders.set(HttpConstants.HttpHeaders.DATABASE_ACCOUNT_NAME,
this.globalDatabaseAccountName);
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
String envName = Configs.getEnvironmentName();
if (StringUtils.isNotEmpty(envName)) {
httpHeaders.set(HttpConstants.HttpHeaders.ENVIRONMENT_NAME, envName);
}
HttpRequest httpRequest = new HttpRequest(HttpMethod.POST, targetEndpoint,
targetEndpoint.getPort(), httpHeaders, fluxBytes);
Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest,
Duration.ofSeconds(Configs.getHttpResponseTimeoutInSeconds()));
return httpResponseMono.flatMap(response -> {
if (response.statusCode() != HttpConstants.StatusCodes.OK) {
logger.error("Client telemetry request did not succeeded, status code {}",
response.statusCode());
}
this.clearDataForNextRun();
return this.sendClientTelemetry();
}).onErrorResume(throwable -> {
logger.error("Error while sending client telemetry request Exception: ", throwable);
this.clearDataForNextRun();
return this.sendClientTelemetry();
});
}
} catch (JsonProcessingException | URISyntaxException ex) {
logger.error("Error while preparing client telemetry. Exception: ", ex);
this.clearDataForNextRun();
return this.sendClientTelemetry();
}
}).onErrorResume(ex -> {
logger.error("sendClientTelemetry() - Unable to send client telemetry" +
". Exception: ", ex);
clearDataForNextRun();
return this.sendClientTelemetry();
}).subscribeOn(scheduler);
}
private void populateAzureVmMetaData(AzureVMMetadata azureVMMetadata) {
this.clientTelemetryInfo.setApplicationRegion(azureVMMetadata.getLocation());
this.clientTelemetryInfo.setMachineId("vmId:" + azureVMMetadata.getVmId());
this.clientTelemetryInfo.setHostEnvInfo(azureVMMetadata.getOsType() + "|" + azureVMMetadata.getSku() +
"|" + azureVMMetadata.getVmSize() + "|" + azureVMMetadata.getAzEnvironment());
}
private static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) {
try {
return OBJECT_MAPPER.readValue(itemResponseBodyAsString, itemClassType);
} catch (IOException e) {
throw new IllegalStateException(
"Failed to parse string [" + itemResponseBodyAsString + "] to POJO.", e);
}
}
private void clearDataForNextRun() {
this.clientTelemetryInfo.getSystemInfoMap().clear();
this.clientTelemetryInfo.getOperationInfoMap().clear();
this.clientTelemetryInfo.getCacheRefreshInfoMap().clear();
for (ConcurrentDoubleHistogram histogram : this.clientTelemetryInfo.getSystemInfoMap().values()) {
histogram.reset();
}
}
private void readHistogram() {
ConcurrentDoubleHistogram cpuHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.CPU_MAX,
ClientTelemetry.CPU_PRECISION);
cpuHistogram.setAutoResize(true);
for (double val : CpuMemoryMonitor.getClientTelemetryCpuLatestList()) {
recordValue(cpuHistogram, val);
}
ReportPayload cpuReportPayload = new ReportPayload(CPU_NAME, CPU_UNIT);
clientTelemetryInfo.getSystemInfoMap().put(cpuReportPayload, cpuHistogram);
ConcurrentDoubleHistogram memoryHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.MEMORY_MAX_IN_MB,
ClientTelemetry.MEMORY_PRECISION);
memoryHistogram.setAutoResize(true);
for (double val : CpuMemoryMonitor.getClientTelemetryMemoryLatestList()) {
recordValue(memoryHistogram, val);
}
ReportPayload memoryReportPayload = new ReportPayload(MEMORY_NAME, MEMORY_UNIT);
clientTelemetryInfo.getSystemInfoMap().put(memoryReportPayload, memoryHistogram);
this.clientTelemetryInfo.setTimeStamp(Instant.now().toString());
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getSystemInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getCacheRefreshInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getOperationInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
}
private void fillMetricsInfo(ReportPayload payload, ConcurrentDoubleHistogram histogram) {
DoubleHistogram copyHistogram = histogram.copy();
payload.getMetricInfo().setCount(copyHistogram.getTotalCount());
payload.getMetricInfo().setMax(copyHistogram.getMaxValue());
payload.getMetricInfo().setMin(copyHistogram.getMinValue());
payload.getMetricInfo().setMean(copyHistogram.getMean());
Map<Double, Double> percentile = new HashMap<>();
percentile.put(PERCENTILE_50, copyHistogram.getValueAtPercentile(PERCENTILE_50));
percentile.put(PERCENTILE_90, copyHistogram.getValueAtPercentile(PERCENTILE_90));
percentile.put(PERCENTILE_95, copyHistogram.getValueAtPercentile(PERCENTILE_95));
percentile.put(PERCENTILE_99, copyHistogram.getValueAtPercentile(PERCENTILE_99));
percentile.put(PERCENTILE_999, copyHistogram.getValueAtPercentile(PERCENTILE_999));
payload.getMetricInfo().setPercentiles(percentile);
}
} |
No - clientId will just allow us to see how many clients they create - not even how many per account. I think clientId will need to get some changes (use account as dimension) - otherwise it isn't very useful. And what I am looking for is a stable identifier across clients across accounts - ideally across the lifecylce of a process - like the "machine name" = turns out machine-name cannot be retrieved in Java reasonably easy (either uses DNS reverse lookup which involves IO or some OS specific APIs) Also it is perfectly fine to create multiple cosmos clients sequentially - like a cache where you drop/close clients for an account when you haven't used it in a while - the main thing we want customers to do when using "singleton" pattern is that they only use one active client per account at any given time. The ClientId also wouldn't help us with that. Bottom-line - clientId is not a replacement for a stable machine identifier - and any changes to clientId can and should be made with a separate PR. | public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) {
try {
this.httpClientInterceptor = httpClientInterceptor;
if (httpClientInterceptor != null) {
this.reactorHttpClient = httpClientInterceptor.apply(httpClient());
}
this.gatewayProxy = createRxGatewayProxy(this.sessionContainer,
this.consistencyLevel,
this.queryCompatibilityMode,
this.userAgentContainer,
this.globalEndpointManager,
this.reactorHttpClient,
this.apiType);
this.globalEndpointManager.init();
this.initializeGatewayConfigurationReader();
if (metadataCachesSnapshot != null) {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy,
metadataCachesSnapshot.getCollectionInfoByNameCache(),
metadataCachesSnapshot.getCollectionInfoByIdCache()
);
} else {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy);
}
this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy);
this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this,
collectionCache);
updateGatewayProxy();
clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(),
ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(),
connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(),
null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions());
clientTelemetry.init();
if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) {
this.storeModel = this.gatewayProxy;
} else {
this.initializeDirectConnectivity();
}
this.retryPolicy.setRxCollectionCache(this.collectionCache);
} catch (Exception e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
} | clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(), | public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) {
try {
this.httpClientInterceptor = httpClientInterceptor;
if (httpClientInterceptor != null) {
this.reactorHttpClient = httpClientInterceptor.apply(httpClient());
}
this.gatewayProxy = createRxGatewayProxy(this.sessionContainer,
this.consistencyLevel,
this.queryCompatibilityMode,
this.userAgentContainer,
this.globalEndpointManager,
this.reactorHttpClient,
this.apiType);
this.globalEndpointManager.init();
this.initializeGatewayConfigurationReader();
if (metadataCachesSnapshot != null) {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy,
metadataCachesSnapshot.getCollectionInfoByNameCache(),
metadataCachesSnapshot.getCollectionInfoByIdCache()
);
} else {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy);
}
this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy);
this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this,
collectionCache);
updateGatewayProxy();
clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(),
ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(),
connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(),
null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions());
clientTelemetry.init();
if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) {
this.storeModel = this.gatewayProxy;
} else {
this.initializeDirectConnectivity();
}
this.retryPolicy.setRxCollectionCache(this.collectionCache);
} catch (Exception e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
} | class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener,
DiagnosticsClientContext {
private static final String tempMachineId = "uuid:" + UUID.randomUUID();
private static final AtomicInteger activeClientsCnt = new AtomicInteger(0);
private static final AtomicInteger clientIdGenerator = new AtomicInteger(0);
private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>(
PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey,
PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false);
private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " +
"ParallelDocumentQueryExecutioncontext, but not used";
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper();
private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer();
private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class);
private final String masterKeyOrResourceToken;
private final URI serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel consistencyLevel;
private final BaseAuthorizationTokenProvider authorizationTokenProvider;
private final UserAgentContainer userAgentContainer;
private final boolean hasAuthKeyResourceToken;
private final Configs configs;
private final boolean connectionSharingAcrossClientsEnabled;
private AzureKeyCredential credential;
private final TokenCredential tokenCredential;
private String[] tokenCredentialScopes;
private SimpleTokenCache tokenCredentialCache;
private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver;
AuthorizationTokenType authorizationTokenType;
private SessionContainer sessionContainer;
private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY;
private RxClientCollectionCache collectionCache;
private RxStoreModel gatewayProxy;
private RxStoreModel storeModel;
private GlobalAddressResolver addressResolver;
private RxPartitionKeyRangeCache partitionKeyRangeCache;
private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap;
private final boolean contentResponseOnWriteEnabled;
private Map<String, PartitionedQueryExecutionInfo> queryPlanCache;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final int clientId;
private ClientTelemetry clientTelemetry;
private ApiType apiType;
private IRetryPolicyFactory resetSessionTokenRetryPolicy;
/**
* Compatibility mode: Allows to specify compatibility mode used by client when
* making query requests. Should be removed when application/sql is no longer
* supported.
*/
private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default;
private final GlobalEndpointManager globalEndpointManager;
private final RetryPolicy retryPolicy;
private HttpClient reactorHttpClient;
private Function<HttpClient, HttpClient> httpClientInterceptor;
private volatile boolean useMultipleWriteLocations;
private StoreClientFactory storeClientFactory;
private GatewayServiceConfigurationReader gatewayConfigurationReader;
private final DiagnosticsClientConfig diagnosticsClientConfig;
private final AtomicBoolean throughputControlEnabled;
private ThroughputControlStore throughputControlStore;
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
private RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
if (permissionFeed != null && permissionFeed.size() > 0) {
this.resourceTokensMap = new HashMap<>();
for (Permission permission : permissionFeed) {
String[] segments = StringUtils.split(permission.getResourceLink(),
Constants.Properties.PATH_SEPARATOR.charAt(0));
if (segments.length <= 0) {
throw new IllegalArgumentException("resourceLink");
}
List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null;
PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false);
if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) {
throw new IllegalArgumentException(permission.getResourceLink());
}
partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName);
if (partitionKeyAndResourceTokenPairs == null) {
partitionKeyAndResourceTokenPairs = new ArrayList<>();
this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs);
}
PartitionKey partitionKey = permission.getResourcePartitionKey();
partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair(
partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty,
permission.getToken()));
logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]",
pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken());
}
if(this.resourceTokensMap.isEmpty()) {
throw new IllegalArgumentException("permissionFeed");
}
String firstToken = permissionFeed.get(0).getToken();
if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) {
this.firstResourceTokenFromPermissionFeed = firstToken;
}
}
}
RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
activeClientsCnt.incrementAndGet();
this.clientId = clientIdGenerator.incrementAndGet();
this.diagnosticsClientConfig = new DiagnosticsClientConfig();
this.diagnosticsClientConfig.withClientId(this.clientId);
this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt);
this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled);
this.diagnosticsClientConfig.withConsistency(consistencyLevel);
this.throughputControlEnabled = new AtomicBoolean(false);
logger.info(
"Initializing DocumentClient [{}] with"
+ " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]",
this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol());
try {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
this.configs = configs;
this.masterKeyOrResourceToken = masterKeyOrResourceToken;
this.serviceEndpoint = serviceEndpoint;
this.credential = credential;
this.tokenCredential = tokenCredential;
this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled;
this.authorizationTokenType = AuthorizationTokenType.Invalid;
if (this.credential != null) {
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.authorizationTokenProvider = null;
hasAuthKeyResourceToken = true;
this.authorizationTokenType = AuthorizationTokenType.ResourceToken;
} else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken);
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else {
hasAuthKeyResourceToken = false;
this.authorizationTokenProvider = null;
if (tokenCredential != null) {
this.tokenCredentialScopes = new String[] {
serviceEndpoint.getScheme() + ":
};
this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential
.getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes)));
this.authorizationTokenType = AuthorizationTokenType.AadToken;
}
}
if (connectionPolicy != null) {
this.connectionPolicy = connectionPolicy;
} else {
this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig());
}
this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode());
this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled());
this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled());
this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions());
this.diagnosticsClientConfig.withMachineId(tempMachineId);
boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled);
this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing);
this.consistencyLevel = consistencyLevel;
this.userAgentContainer = new UserAgentContainer();
String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix();
if (userAgentSuffix != null && userAgentSuffix.length() > 0) {
userAgentContainer.setSuffix(userAgentSuffix);
}
this.httpClientInterceptor = null;
this.reactorHttpClient = httpClient();
this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs);
this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy);
this.resetSessionTokenRetryPolicy = retryPolicy;
CpuMemoryMonitor.register(this);
this.queryPlanCache = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE));
this.apiType = apiType;
} catch (RuntimeException e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
}
@Override
public DiagnosticsClientConfig getConfig() {
return diagnosticsClientConfig;
}
@Override
public CosmosDiagnostics createDiagnostics() {
return BridgeInternal.createCosmosDiagnostics(this, this.globalEndpointManager);
}
private void initializeGatewayConfigurationReader() {
this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager);
DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount();
if (databaseAccount == null) {
logger.error("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
throw new RuntimeException("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
}
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount);
}
private void updateGatewayProxy() {
((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader);
((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache);
((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache);
((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations);
}
public void serialize(CosmosClientMetadataCachesSnapshot state) {
RxCollectionCache.serialize(state, this.collectionCache);
}
private void initializeDirectConnectivity() {
this.addressResolver = new GlobalAddressResolver(this,
this.reactorHttpClient,
this.globalEndpointManager,
this.configs.getProtocol(),
this,
this.collectionCache,
this.partitionKeyRangeCache,
userAgentContainer,
null,
this.connectionPolicy,
this.apiType);
this.storeClientFactory = new StoreClientFactory(
this.addressResolver,
this.diagnosticsClientConfig,
this.configs,
this.connectionPolicy,
this.userAgentContainer,
this.connectionSharingAcrossClientsEnabled,
this.clientTelemetry
);
this.createStoreModel(true);
}
DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() {
return new DatabaseAccountManagerInternal() {
@Override
public URI getServiceEndpoint() {
return RxDocumentClientImpl.this.getServiceEndpoint();
}
@Override
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
logger.info("Getting database account endpoint from {}", endpoint);
return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return RxDocumentClientImpl.this.getConnectionPolicy();
}
};
}
RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer,
ConsistencyLevel consistencyLevel,
QueryCompatibilityMode queryCompatibilityMode,
UserAgentContainer userAgentContainer,
GlobalEndpointManager globalEndpointManager,
HttpClient httpClient,
ApiType apiType) {
return new RxGatewayStoreModel(
this,
sessionContainer,
consistencyLevel,
queryCompatibilityMode,
userAgentContainer,
globalEndpointManager,
httpClient,
apiType);
}
private HttpClient httpClient() {
HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs)
.withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout())
.withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize())
.withProxy(this.connectionPolicy.getProxy())
.withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout());
if (connectionSharingAcrossClientsEnabled) {
return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig);
} else {
diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig);
return HttpClient.createFixed(httpClientConfig);
}
}
private void createStoreModel(boolean subscribeRntbdStatus) {
StoreClient storeClient = this.storeClientFactory.createStoreClient(this,
this.addressResolver,
this.sessionContainer,
this.gatewayConfigurationReader,
this,
this.useMultipleWriteLocations
);
this.storeModel = new ServerStoreModel(storeClient);
}
@Override
public URI getServiceEndpoint() {
return this.serviceEndpoint;
}
@Override
public URI getWriteEndpoint() {
return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null);
}
@Override
public URI getReadEndpoint() {
return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return this.connectionPolicy;
}
@Override
public boolean isContentResponseOnWriteEnabled() {
return contentResponseOnWriteEnabled;
}
@Override
public ConsistencyLevel getConsistencyLevel() {
return consistencyLevel;
}
@Override
public ClientTelemetry getClientTelemetry() {
return this.clientTelemetry;
}
@Override
public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (database == null) {
throw new IllegalArgumentException("Database");
}
logger.debug("Creating a Database. id: [{}]", database.getId());
validateResource(database);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Reading a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT);
}
private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) {
switch (resourceTypeEnum) {
case Database:
return Paths.DATABASES_ROOT;
case DocumentCollection:
return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT);
case Document:
return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT);
case Offer:
return Paths.OFFERS_ROOT;
case User:
return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT);
case ClientEncryptionKey:
return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
case Permission:
return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT);
case Attachment:
return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT);
case StoredProcedure:
return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
case Trigger:
return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT);
case UserDefinedFunction:
return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
case Conflict:
return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT);
default:
throw new IllegalArgumentException("resource type not supported");
}
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) {
if (options == null) {
return null;
}
return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options);
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) {
if (options == null) {
return null;
}
return options.getOperationContextAndListenerTuple();
}
private <T extends Resource> Flux<FeedResponse<T>> createQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum) {
String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum);
UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getCorrelationActivityId(options);
UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ?
correlationActivityIdOfRequestOptions : Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this,
getOperationContextAndListenerTuple(options));
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> createQueryInternal(
resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId),
invalidPartitionExceptionRetryPolicy);
}
private <T extends Resource> Flux<FeedResponse<T>> createQueryInternal(
String resourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
IDocumentQueryClient queryClient,
UUID activityId) {
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory
.createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery,
options, resourceLink, false, activityId,
Configs.isQueryPlanCachingEnabled(), queryPlanCache);
AtomicBoolean isFirstResponse = new AtomicBoolean(true);
return executionContext.flatMap(iDocumentQueryExecutionContext -> {
QueryInfo queryInfo = null;
if (iDocumentQueryExecutionContext instanceof PipelinedDocumentQueryExecutionContext) {
queryInfo = ((PipelinedDocumentQueryExecutionContext<T>) iDocumentQueryExecutionContext).getQueryInfo();
}
QueryInfo finalQueryInfo = queryInfo;
return iDocumentQueryExecutionContext.executeAsync()
.map(tFeedResponse -> {
if (finalQueryInfo != null) {
if (finalQueryInfo.hasSelectValue()) {
ModelBridgeInternal
.addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo);
}
if (isFirstResponse.compareAndSet(true, false)) {
ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse,
finalQueryInfo.getQueryPlanDiagnosticsContext());
}
}
return tFeedResponse;
});
});
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) {
return queryDatabases(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database);
}
@Override
public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink,
DocumentCollection collection, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink,
DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink,
collection.getId());
validateResource(collection);
String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
});
} catch (Exception e) {
logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Replacing a Collection. id: [{}]", collection.getId());
validateResource(collection);
String path = Utils.joinPath(collection.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
if (resourceResponse.getResource() != null) {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
}
});
} catch (Exception e) {
logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.DELETE)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated));
}
private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated ->
this.getStoreProxy(requestPopulated).processMessage(requestPopulated)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
));
}
@Override
public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class,
Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection);
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection);
}
private static String serializeProcedureParams(List<Object> objectArray) {
String[] stringArray = new String[objectArray.size()];
for (int i = 0; i < objectArray.size(); ++i) {
Object object = objectArray.get(i);
if (object instanceof JsonSerializable) {
stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object);
} else {
try {
stringArray[i] = mapper.writeValueAsString(object);
} catch (IOException e) {
throw new IllegalArgumentException("Can't serialize the object into the json string", e);
}
}
}
return String.format("[%s]", StringUtils.join(stringArray, ","));
}
private static void validateResource(Resource resource) {
if (!StringUtils.isEmpty(resource.getId())) {
if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 ||
resource.getId().indexOf('?') != -1 || resource.getId().indexOf('
throw new IllegalArgumentException("Id contains illegal chars.");
}
if (resource.getId().endsWith(" ")) {
throw new IllegalArgumentException("Id ends with a space.");
}
}
}
private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) {
Map<String, String> headers = new HashMap<>();
if (this.useMultipleWriteLocations) {
headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString());
}
if (consistencyLevel != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString());
}
if (options == null) {
if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
return headers;
}
Map<String, String> customOptions = options.getHeaders();
if (customOptions != null) {
headers.putAll(customOptions);
}
boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled;
if (options.isContentResponseOnWriteEnabled() != null) {
contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled();
}
if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
if (options.getIfMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag());
}
if(options.getIfNoneMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag());
}
if (options.getConsistencyLevel() != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString());
}
if (options.getIndexingDirective() != null) {
headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString());
}
if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) {
String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude);
}
if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) {
String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude);
}
if (!Strings.isNullOrEmpty(options.getSessionToken())) {
headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken());
}
if (options.getResourceTokenExpirySeconds() != null) {
headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY,
String.valueOf(options.getResourceTokenExpirySeconds()));
}
if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString());
} else if (options.getOfferType() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType());
}
if (options.getOfferThroughput() == null) {
if (options.getThroughputProperties() != null) {
Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties());
final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings();
OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null;
if (offerAutoscaleSettings != null) {
autoscaleAutoUpgradeProperties
= offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties();
}
if (offer.hasOfferThroughput() &&
(offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 ||
autoscaleAutoUpgradeProperties != null &&
autoscaleAutoUpgradeProperties
.getAutoscaleThroughputProperties()
.getIncrementPercent() >= 0)) {
throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with "
+ "fixed offer");
}
if (offer.hasOfferThroughput()) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput()));
} else if (offer.getOfferAutoScaleSettings() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS,
ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings()));
}
}
}
if (options.isQuotaInfoEnabled()) {
headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true));
}
if (options.isScriptLoggingEnabled()) {
headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true));
}
if (options.getDedicatedGatewayRequestOptions() != null &&
options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) {
headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS,
String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions())));
}
return headers;
}
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return this.resetSessionTokenRetryPolicy;
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Document document,
RequestOptions options) {
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs
.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object document,
RequestOptions options,
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) {
return collectionObs.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private void addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object objectDoc, RequestOptions options,
DocumentCollection collection) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
PartitionKeyInternal partitionKeyInternal = null;
if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else if (options != null && options.getPartitionKey() != null) {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey());
} else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) {
partitionKeyInternal = PartitionKeyInternal.getEmpty();
} else if (contentAsByteBuffer != null || objectDoc != null) {
InternalObjectNode internalObjectNode;
if (objectDoc instanceof InternalObjectNode) {
internalObjectNode = (InternalObjectNode) objectDoc;
} else if (objectDoc instanceof ObjectNode) {
internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc);
} else if (contentAsByteBuffer != null) {
contentAsByteBuffer.rewind();
internalObjectNode = new InternalObjectNode(contentAsByteBuffer);
} else {
throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null");
}
Instant serializationStartTime = Instant.now();
partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTime,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION
);
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
} else {
throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation.");
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
}
public static PartitionKeyInternal extractPartitionKeyValueFromDocument(
InternalObjectNode document,
PartitionKeyDefinition partitionKeyDefinition) {
if (partitionKeyDefinition != null) {
switch (partitionKeyDefinition.getKind()) {
case HASH:
String path = partitionKeyDefinition.getPaths().iterator().next();
List<String> parts = PathParser.getPathParts(path);
if (parts.size() >= 1) {
Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts);
if (value == null || value.getClass() == ObjectNode.class) {
value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
}
if (value instanceof PartitionKeyInternal) {
return (PartitionKeyInternal) value;
} else {
return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false);
}
}
break;
case MULTI_HASH:
Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()];
for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){
String partitionPath = partitionKeyDefinition.getPaths().get(pathIter);
List<String> partitionPathParts = PathParser.getPathParts(partitionPath);
partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts);
}
return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false);
default:
throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind());
}
}
return null;
}
private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
Object document,
RequestOptions options,
boolean disableAutomaticIdGeneration,
OperationType operationType) {
if (StringUtils.isEmpty(documentCollectionLink)) {
throw new IllegalArgumentException("documentCollectionLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Document, path, requestHeaders, options, content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return addPartitionKeyInformation(request, content, document, options, collectionObs);
}
private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink");
checkNotNull(serverBatchRequest, "expected non null serverBatchRequest");
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody()));
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Batch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> {
addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v);
return request;
});
}
private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request,
ServerBatchRequest serverBatchRequest,
DocumentCollection collection) {
if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) {
PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue();
PartitionKeyInternal partitionKeyInternal;
if (partitionKey.equals(PartitionKey.NONE)) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey);
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
} else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) {
request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId()));
} else {
throw new UnsupportedOperationException("Unknown Server request.");
}
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString());
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch()));
request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError()));
request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size());
return request;
}
private Mono<RxDocumentServiceRequest> populateHeaders(RxDocumentServiceRequest request, RequestVerb httpMethod) {
request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123());
if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null
|| this.cosmosAuthorizationTokenResolver != null || this.credential != null) {
String resourceName = request.getResourceAddress();
String authorization = this.getUserAuthorizationToken(
resourceName, request.getResourceType(), httpMethod, request.getHeaders(),
AuthorizationTokenType.PrimaryMasterKey, request.properties);
try {
authorization = URLEncoder.encode(authorization, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Failed to encode authtoken.", e);
}
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
}
if (this.apiType != null) {
request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString());
}
if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod))
&& !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
}
if (RequestVerb.PATCH.equals(httpMethod) &&
!request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH);
}
if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) {
request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
}
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
if (this.requiresFeedRangeFiltering(request)) {
return request.getFeedRange()
.populateFeedRangeFilteringHeaders(
this.getPartitionKeyRangeCache(),
request,
this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request))
.flatMap(this::populateAuthorizationHeader);
}
return this.populateAuthorizationHeader(request);
}
private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) {
if (request.getResourceType() != ResourceType.Document &&
request.getResourceType() != ResourceType.Conflict) {
return false;
}
switch (request.getOperationType()) {
case ReadFeed:
case Query:
case SqlQuery:
return request.getFeedRange() != null;
default:
return false;
}
}
@Override
public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) {
if (request == null) {
throw new IllegalArgumentException("request");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return request;
});
} else {
return Mono.just(request);
}
}
@Override
public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) {
if (httpHeaders == null) {
throw new IllegalArgumentException("httpHeaders");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return httpHeaders;
});
}
return Mono.just(httpHeaders);
}
@Override
public AuthorizationTokenType getAuthorizationTokenType() {
return this.authorizationTokenType;
}
@Override
public String getUserAuthorizationToken(String resourceName,
ResourceType resourceType,
RequestVerb requestVerb,
Map<String, String> headers,
AuthorizationTokenType tokenType,
Map<String, Object> properties) {
if (this.cosmosAuthorizationTokenResolver != null) {
return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(),
properties != null ? Collections.unmodifiableMap(properties) : null);
} else if (credential != null) {
return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName,
resourceType, headers);
} else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) {
return masterKeyOrResourceToken;
} else {
assert resourceTokensMap != null;
if(resourceType.equals(ResourceType.DatabaseAccount)) {
return this.firstResourceTokenFromPermissionFeed;
}
return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers);
}
}
private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) {
CosmosResourceType cosmosResourceType =
ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString());
if (cosmosResourceType == null) {
return CosmosResourceType.SYSTEM;
}
return cosmosResourceType;
}
void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) {
this.sessionContainer.setSessionToken(request, response.getResponseHeaders());
}
private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
Map<String, String> headers = requestPopulated.getHeaders();
assert (headers != null);
headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true");
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
);
});
}
private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.PUT)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PATCH);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(request).processMessage(request);
}
@Override
public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) {
try {
logger.debug("Creating a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Create);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance);
}
private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Upsert);
Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = Utils.getCollectionName(documentLink);
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Document typedDocument = documentFromObject(document, mapper);
return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = document.getSelfLink();
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (document == null) {
throw new IllegalArgumentException("document");
}
return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a database due to [{}]", e.getMessage());
return Mono.error(e);
}
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink,
Document document,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
if (document == null) {
throw new IllegalArgumentException("document");
}
logger.debug("Replacing a Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = serializeJsonToByteBuffer(document);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs);
return requestObs.flatMap(req -> replace(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> patchDocument(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink");
checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations");
logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options));
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Patch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(
request,
null,
null,
options,
collectionObs);
return requestObs.flatMap(req -> patch(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy);
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Deleting a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs);
return requestObs.flatMap(req -> this
.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> this
.deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting documents due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Reading a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> {
return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Document>> readDocuments(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return queryDocuments(collectionLink, "SELECT * FROM r", options);
}
@Override
public <T> Mono<FeedResponse<T>> readMany(
List<CosmosItemIdentity> itemIdentityList,
String collectionLink,
CosmosQueryRequestOptions options,
Class<T> klass) {
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink, null
);
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request);
return collectionObs
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache
.tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null);
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap =
new HashMap<>();
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
itemIdentityList
.forEach(itemIdentity -> {
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(
itemIdentity.getPartitionKey()),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
if (partitionRangeItemKeyMap.get(range) == null) {
List<CosmosItemIdentity> list = new ArrayList<>();
list.add(itemIdentity);
partitionRangeItemKeyMap.put(range, list);
} else {
List<CosmosItemIdentity> pairs =
partitionRangeItemKeyMap.get(range);
pairs.add(itemIdentity);
partitionRangeItemKeyMap.put(range, pairs);
}
});
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap;
rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap,
collection.getPartitionKey());
return createReadManyQuery(
resourceLink,
new SqlQuerySpec(DUMMY_SQL_QUERY),
options,
Document.class,
ResourceType.Document,
collection,
Collections.unmodifiableMap(rangeQueryMap))
.collectList()
.map(feedList -> {
List<T> finalList = new ArrayList<>();
HashMap<String, String> headers = new HashMap<>();
ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>();
double requestCharge = 0;
for (FeedResponse<Document> page : feedList) {
ConcurrentMap<String, QueryMetrics> pageQueryMetrics =
ModelBridgeInternal.queryMetrics(page);
if (pageQueryMetrics != null) {
pageQueryMetrics.forEach(
aggregatedQueryMetrics::putIfAbsent);
}
requestCharge += page.getRequestCharge();
finalList.addAll(page.getResults().stream().map(document ->
ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList()));
}
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double
.toString(requestCharge));
FeedResponse<T> frp = BridgeInternal
.createFeedResponse(finalList, headers);
return frp;
});
});
}
);
}
private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap(
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap,
PartitionKeyDefinition partitionKeyDefinition) {
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>();
String partitionKeySelector = createPkSelector(partitionKeyDefinition);
for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) {
SqlQuerySpec sqlQuerySpec;
if (partitionKeySelector.equals("[\"id\"]")) {
sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector);
} else {
sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector);
}
rangeQueryMap.put(entry.getKey(), sqlQuerySpec);
}
return rangeQueryMap;
}
private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(
List<CosmosItemIdentity> idPartitionKeyPairList,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( ");
for (int i = 0; i < idPartitionKeyPairList.size(); i++) {
CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i);
String idValue = itemIdentity.getId();
String idParamName = "@param" + i;
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
if (!Objects.equals(idValue, pkValue)) {
continue;
}
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append(idParamName);
if (i < idPartitionKeyPairList.size() - 1) {
queryStringBuilder.append(", ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE ( ");
for (int i = 0; i < itemIdentities.size(); i++) {
CosmosItemIdentity itemIdentity = itemIdentities.get(i);
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
String pkParamName = "@param" + (2 * i);
parameters.add(new SqlParameter(pkParamName, pkValue));
String idValue = itemIdentity.getId();
String idParamName = "@param" + (2 * i + 1);
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append("(");
queryStringBuilder.append("c.id = ");
queryStringBuilder.append(idParamName);
queryStringBuilder.append(" AND ");
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
queryStringBuilder.append(" )");
if (i < itemIdentities.size() - 1) {
queryStringBuilder.append(" OR ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) {
return partitionKeyDefinition.getPaths()
.stream()
.map(pathPart -> StringUtils.substring(pathPart, 1))
.map(pathPart -> StringUtils.replace(pathPart, "\"", "\\"))
.map(part -> "[\"" + part + "\"]")
.collect(Collectors.joining());
}
private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
DocumentCollection collection,
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) {
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(),
sqlQuery,
rangeQueryMap,
options,
collection.getResourceId(),
parentResourceLink,
activityId,
klass,
resourceTypeEnum);
return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync);
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, String query, CosmosQueryRequestOptions options) {
return queryDocuments(collectionLink, new SqlQuerySpec(query), options);
}
private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return new IDocumentQueryClient () {
@Override
public RxCollectionCache getCollectionCache() {
return RxDocumentClientImpl.this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return RxDocumentClientImpl.this.partitionKeyRangeCache;
}
@Override
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy;
}
@Override
public ConsistencyLevel getDefaultConsistencyLevelAsync() {
return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel();
}
@Override
public ConsistencyLevel getDesiredConsistencyLevelAsync() {
return RxDocumentClientImpl.this.consistencyLevel;
}
@Override
public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) {
if (operationContextAndListenerTuple == null) {
return RxDocumentClientImpl.this.query(request).single();
} else {
final OperationListener listener =
operationContextAndListenerTuple.getOperationListener();
final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext();
request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId());
listener.requestListener(operationContext, request);
return RxDocumentClientImpl.this.query(request).single().doOnNext(
response -> listener.responseListener(operationContext, response)
).doOnError(
ex -> listener.exceptionListener(operationContext, ex)
);
}
}
@Override
public QueryCompatibilityMode getQueryCompatibilityMode() {
return QueryCompatibilityMode.Default;
}
@Override
public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) {
return null;
}
};
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
SqlQuerySpecLogger.getInstance().logQuery(querySpec);
return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document);
}
@Override
public Flux<FeedResponse<Document>> queryDocumentChangeFeed(
final DocumentCollection collection,
final CosmosChangeFeedRequestOptions changeFeedOptions) {
checkNotNull(collection, "Argument 'collection' must not be null.");
ChangeFeedQueryImpl<Document> changeFeedQueryImpl = new ChangeFeedQueryImpl<>(
this,
ResourceType.Document,
Document.class,
collection.getAltLink(),
collection.getResourceId(),
changeFeedOptions);
return changeFeedQueryImpl.executeAsync();
}
@Override
public Flux<FeedResponse<Document>> readAllDocuments(
String collectionLink,
PartitionKey partitionKey,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (partitionKey == null) {
throw new IllegalArgumentException("partitionKey");
}
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null
);
Flux<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request).flux();
return collectionObs.flatMap(documentCollectionResourceResponse -> {
DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
String pkSelector = createPkSelector(pkDefinition);
SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector);
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
final CosmosQueryRequestOptions effectiveOptions =
ModelBridgeInternal.createQueryRequestOptions(options);
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> {
Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache
.tryLookupAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null).flux();
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(partitionKey),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
return createQueryInternal(
resourceLink,
querySpec,
ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()),
Document.class,
ResourceType.Document,
queryClient,
activityId);
});
},
invalidPartitionExceptionRetryPolicy);
});
}
@Override
public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() {
return queryPlanCache;
}
@Override
public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class,
Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT));
}
private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
validateResource(storedProcedure);
String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType,
ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
return request;
}
private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (udf == null) {
throw new IllegalArgumentException("udf");
}
validateResource(udf);
String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Create);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId());
RxDocumentClientImpl.validateResource(storedProcedure);
String path = Utils.joinPath(storedProcedure.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class,
Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
List<Object> procedureParams) {
return this.executeStoredProcedure(storedProcedureLink, null, procedureParams);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy);
}
@Override
public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy);
}
private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) {
try {
logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript);
requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ExecuteJavaScript,
ResourceType.StoredProcedure, path,
procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "",
requestHeaders, options);
if (retryPolicy != null) {
retryPolicy.onBeforeSendRequest(request);
}
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options))
.map(response -> {
this.captureSessionToken(request, response);
return toStoredProcedureResponse(response);
}));
} catch (Exception e) {
logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
DocumentClientRetryPolicy requestRetryPolicy,
boolean disableAutomaticIdGeneration) {
try {
logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size());
Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true));
} catch (Exception ex) {
logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex);
return Mono.error(ex);
}
}
@Override
public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path,
trigger, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId());
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(trigger.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Trigger, Trigger.class,
Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryTriggers(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger);
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (udf == null) {
throw new IllegalArgumentException("udf");
}
logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId());
validateResource(udf);
String path = Utils.joinPath(udf.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class,
Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
String query, CosmosQueryRequestOptions options) {
return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction);
}
@Override
public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Conflict, Conflict.class,
Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryConflicts(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict);
}
@Override
public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (user == null) {
throw new IllegalArgumentException("user");
}
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.User, path, user, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (user == null) {
throw new IllegalArgumentException("user");
}
logger.debug("Replacing a User. user id [{}]", user.getId());
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(user.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.User, path, user, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Deleting a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Reading a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.User, User.class,
Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) {
return queryUsers(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User);
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(clientEncryptionKeyLink)) {
throw new IllegalArgumentException("clientEncryptionKeyLink");
}
logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink);
String path = Utils.joinPath(clientEncryptionKeyLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink,
ClientEncryptionKey clientEncryptionKey, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId());
RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey,
String nameBasedLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey,
nameBasedLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId());
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(nameBasedLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey,
OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders,
options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class,
Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey);
}
@Override
public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy());
}
private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
if (permission == null) {
throw new IllegalArgumentException("permission");
}
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Permission, path, permission, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (permission == null) {
throw new IllegalArgumentException("permission");
}
logger.debug("Replacing a Permission. permission id [{}]", permission.getId());
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(permission.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Reading a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
return readFeed(options, ResourceType.Permission, Permission.class,
Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query,
CosmosQueryRequestOptions options) {
return queryPermissions(userLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission);
}
@Override
public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
if (offer == null) {
throw new IllegalArgumentException("offer");
}
logger.debug("Replacing an Offer. offer id [{}]", offer.getId());
RxDocumentClientImpl.validateResource(offer);
String path = Utils.joinPath(offer.getSelfLink(), null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace,
ResourceType.Offer, path, offer, null, null);
return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Offer>> readOffer(String offerLink) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(offerLink)) {
throw new IllegalArgumentException("offerLink");
}
logger.debug("Reading an Offer. offerLink [{}]", offerLink);
String path = Utils.joinPath(offerLink, null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Offer, Offer.class,
Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null));
}
private <T extends Resource> Flux<FeedResponse<T>> readFeed(CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options);
int maxPageSize = maxItemCount != null ? maxItemCount : -1;
final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options;
DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> {
Map<String, String> requestHeaders = new HashMap<>();
if (continuationToken != null) {
requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken);
}
requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize));
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions);
retryPolicy.onBeforeSendRequest(request);
return request;
};
Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper
.inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)),
retryPolicy);
return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, maxPageSize);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) {
return queryOffers(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer);
}
@Override
public Mono<DatabaseAccount> getDatabaseAccount() {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy),
documentClientRetryPolicy);
}
@Override
public DatabaseAccount getLatestDatabaseAccount() {
return this.globalEndpointManager.getLatestDatabaseAccount();
}
private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Getting Database Account");
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read,
ResourceType.DatabaseAccount, "",
(HashMap<String, String>) null,
null);
return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount);
} catch (Exception e) {
logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Object getSession() {
return this.sessionContainer;
}
public void setSession(Object sessionContainer) {
this.sessionContainer = (SessionContainer) sessionContainer;
}
@Override
public RxClientCollectionCache getCollectionCache() {
return this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return partitionKeyRangeCache;
}
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
return Flux.defer(() -> {
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null);
return this.populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
requestPopulated.setEndpointOverride(endpoint);
return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> {
String message = String.format("Failed to retrieve database account information. %s",
e.getCause() != null
? e.getCause().toString()
: e.toString());
logger.warn(message);
}).map(rsp -> rsp.getResource(DatabaseAccount.class))
.doOnNext(databaseAccount ->
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled()
&& BridgeInternal.isEnableMultipleWriteLocations(databaseAccount));
});
});
}
/**
* Certain requests must be routed through gateway even when the client connectivity mode is direct.
*
* @param request
* @return RxStoreModel
*/
private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) {
if (request.UseGatewayMode) {
return this.gatewayProxy;
}
ResourceType resourceType = request.getResourceType();
OperationType operationType = request.getOperationType();
if (resourceType == ResourceType.Offer ||
resourceType == ResourceType.ClientEncryptionKey ||
resourceType.isScript() && operationType != OperationType.ExecuteJavaScript ||
resourceType == ResourceType.PartitionKeyRange ||
resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) {
return this.gatewayProxy;
}
if (operationType == OperationType.Create
|| operationType == OperationType.Upsert) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection ||
resourceType == ResourceType.Permission) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Delete) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Replace) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Read) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else {
if ((operationType == OperationType.Query ||
operationType == OperationType.SqlQuery ||
operationType == OperationType.ReadFeed) &&
Utils.isCollectionChild(request.getResourceType())) {
if (request.getPartitionKeyRangeIdentity() == null &&
request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) {
return this.gatewayProxy;
}
}
return this.storeModel;
}
}
@Override
public void close() {
logger.info("Attempting to close client {}", this.clientId);
if (!closed.getAndSet(true)) {
this.activeClientsCnt.decrementAndGet();
logger.info("Shutting down ...");
logger.info("Closing Global Endpoint Manager ...");
LifeCycleUtils.closeQuietly(this.globalEndpointManager);
logger.info("Closing StoreClientFactory ...");
LifeCycleUtils.closeQuietly(this.storeClientFactory);
logger.info("Shutting down reactorHttpClient ...");
LifeCycleUtils.closeQuietly(this.reactorHttpClient);
logger.info("Shutting down CpuMonitor ...");
CpuMemoryMonitor.unregister(this);
if (this.throughputControlEnabled.get()) {
logger.info("Closing ThroughputControlStore ...");
this.throughputControlStore.close();
}
logger.info("Shutting down completed.");
} else {
logger.warn("Already shutdown!");
}
}
@Override
public ItemDeserializer getItemDeserializer() {
return this.itemDeserializer;
}
@Override
public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group can not be null");
if (this.throughputControlEnabled.compareAndSet(false, true)) {
this.throughputControlStore =
new ThroughputControlStore(
this.collectionCache,
this.connectionPolicy.getConnectionMode(),
this.partitionKeyRangeCache);
this.storeModel.enableThroughputControl(throughputControlStore);
}
this.throughputControlStore.enableThroughputControlGroup(group);
}
private static SqlQuerySpec createLogicalPartitionScanQuerySpec(
PartitionKey partitionKey,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE");
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey);
String pkParamName = "@pkValue";
parameters.add(new SqlParameter(pkParamName, pkValue));
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
@Override
public Mono<List<FeedRange>> getFeedRanges(String collectionLink) {
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
collectionLink,
new HashMap<>());
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null);
invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request);
return ObservableHelper.inlineIfPossibleAsObs(
() -> getFeedRangesInternal(request, collectionLink),
invalidPartitionExceptionRetryPolicy);
}
private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) {
logger.debug("getFeedRange collectionLink=[{}]", collectionLink);
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null,
request);
return collectionObs.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache
.tryGetOverlappingRangesAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null);
return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request));
});
}
private static List<FeedRange> toFeedRanges(
Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) {
final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v;
if (partitionKeyRangeList == null) {
request.forceNameCacheRefresh = true;
throw new InvalidPartitionException();
}
List<FeedRange> feedRanges = new ArrayList<>();
partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange)));
return feedRanges;
}
private static FeedRange toFeedRange(PartitionKeyRange pkRange) {
return new FeedRangeEpkImpl(pkRange.toRange());
}
} | class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener,
DiagnosticsClientContext {
private static final String tempMachineId = "uuid:" + UUID.randomUUID();
private static final AtomicInteger activeClientsCnt = new AtomicInteger(0);
private static final AtomicInteger clientIdGenerator = new AtomicInteger(0);
private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>(
PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey,
PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false);
private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " +
"ParallelDocumentQueryExecutioncontext, but not used";
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper();
private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer();
private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class);
private final String masterKeyOrResourceToken;
private final URI serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel consistencyLevel;
private final BaseAuthorizationTokenProvider authorizationTokenProvider;
private final UserAgentContainer userAgentContainer;
private final boolean hasAuthKeyResourceToken;
private final Configs configs;
private final boolean connectionSharingAcrossClientsEnabled;
private AzureKeyCredential credential;
private final TokenCredential tokenCredential;
private String[] tokenCredentialScopes;
private SimpleTokenCache tokenCredentialCache;
private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver;
AuthorizationTokenType authorizationTokenType;
private SessionContainer sessionContainer;
private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY;
private RxClientCollectionCache collectionCache;
private RxStoreModel gatewayProxy;
private RxStoreModel storeModel;
private GlobalAddressResolver addressResolver;
private RxPartitionKeyRangeCache partitionKeyRangeCache;
private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap;
private final boolean contentResponseOnWriteEnabled;
private Map<String, PartitionedQueryExecutionInfo> queryPlanCache;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final int clientId;
private ClientTelemetry clientTelemetry;
private ApiType apiType;
private IRetryPolicyFactory resetSessionTokenRetryPolicy;
/**
* Compatibility mode: Allows to specify compatibility mode used by client when
* making query requests. Should be removed when application/sql is no longer
* supported.
*/
private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default;
private final GlobalEndpointManager globalEndpointManager;
private final RetryPolicy retryPolicy;
private HttpClient reactorHttpClient;
private Function<HttpClient, HttpClient> httpClientInterceptor;
private volatile boolean useMultipleWriteLocations;
private StoreClientFactory storeClientFactory;
private GatewayServiceConfigurationReader gatewayConfigurationReader;
private final DiagnosticsClientConfig diagnosticsClientConfig;
private final AtomicBoolean throughputControlEnabled;
private ThroughputControlStore throughputControlStore;
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
private RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
if (permissionFeed != null && permissionFeed.size() > 0) {
this.resourceTokensMap = new HashMap<>();
for (Permission permission : permissionFeed) {
String[] segments = StringUtils.split(permission.getResourceLink(),
Constants.Properties.PATH_SEPARATOR.charAt(0));
if (segments.length <= 0) {
throw new IllegalArgumentException("resourceLink");
}
List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null;
PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false);
if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) {
throw new IllegalArgumentException(permission.getResourceLink());
}
partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName);
if (partitionKeyAndResourceTokenPairs == null) {
partitionKeyAndResourceTokenPairs = new ArrayList<>();
this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs);
}
PartitionKey partitionKey = permission.getResourcePartitionKey();
partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair(
partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty,
permission.getToken()));
logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]",
pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken());
}
if(this.resourceTokensMap.isEmpty()) {
throw new IllegalArgumentException("permissionFeed");
}
String firstToken = permissionFeed.get(0).getToken();
if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) {
this.firstResourceTokenFromPermissionFeed = firstToken;
}
}
}
RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
activeClientsCnt.incrementAndGet();
this.clientId = clientIdGenerator.incrementAndGet();
this.diagnosticsClientConfig = new DiagnosticsClientConfig();
this.diagnosticsClientConfig.withClientId(this.clientId);
this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt);
this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled);
this.diagnosticsClientConfig.withConsistency(consistencyLevel);
this.throughputControlEnabled = new AtomicBoolean(false);
logger.info(
"Initializing DocumentClient [{}] with"
+ " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]",
this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol());
try {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
this.configs = configs;
this.masterKeyOrResourceToken = masterKeyOrResourceToken;
this.serviceEndpoint = serviceEndpoint;
this.credential = credential;
this.tokenCredential = tokenCredential;
this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled;
this.authorizationTokenType = AuthorizationTokenType.Invalid;
if (this.credential != null) {
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.authorizationTokenProvider = null;
hasAuthKeyResourceToken = true;
this.authorizationTokenType = AuthorizationTokenType.ResourceToken;
} else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken);
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else {
hasAuthKeyResourceToken = false;
this.authorizationTokenProvider = null;
if (tokenCredential != null) {
this.tokenCredentialScopes = new String[] {
serviceEndpoint.getScheme() + ":
};
this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential
.getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes)));
this.authorizationTokenType = AuthorizationTokenType.AadToken;
}
}
if (connectionPolicy != null) {
this.connectionPolicy = connectionPolicy;
} else {
this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig());
}
this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode());
this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled());
this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled());
this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions());
this.diagnosticsClientConfig.withMachineId(tempMachineId);
boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled);
this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing);
this.consistencyLevel = consistencyLevel;
this.userAgentContainer = new UserAgentContainer();
String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix();
if (userAgentSuffix != null && userAgentSuffix.length() > 0) {
userAgentContainer.setSuffix(userAgentSuffix);
}
this.httpClientInterceptor = null;
this.reactorHttpClient = httpClient();
this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs);
this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy);
this.resetSessionTokenRetryPolicy = retryPolicy;
CpuMemoryMonitor.register(this);
this.queryPlanCache = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE));
this.apiType = apiType;
} catch (RuntimeException e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
}
@Override
public DiagnosticsClientConfig getConfig() {
return diagnosticsClientConfig;
}
@Override
public CosmosDiagnostics createDiagnostics() {
return BridgeInternal.createCosmosDiagnostics(this, this.globalEndpointManager);
}
private void initializeGatewayConfigurationReader() {
this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager);
DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount();
if (databaseAccount == null) {
logger.error("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
throw new RuntimeException("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
}
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount);
}
private void updateGatewayProxy() {
((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader);
((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache);
((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache);
((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations);
}
public void serialize(CosmosClientMetadataCachesSnapshot state) {
RxCollectionCache.serialize(state, this.collectionCache);
}
private void initializeDirectConnectivity() {
this.addressResolver = new GlobalAddressResolver(this,
this.reactorHttpClient,
this.globalEndpointManager,
this.configs.getProtocol(),
this,
this.collectionCache,
this.partitionKeyRangeCache,
userAgentContainer,
null,
this.connectionPolicy,
this.apiType);
this.storeClientFactory = new StoreClientFactory(
this.addressResolver,
this.diagnosticsClientConfig,
this.configs,
this.connectionPolicy,
this.userAgentContainer,
this.connectionSharingAcrossClientsEnabled,
this.clientTelemetry
);
this.createStoreModel(true);
}
DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() {
return new DatabaseAccountManagerInternal() {
@Override
public URI getServiceEndpoint() {
return RxDocumentClientImpl.this.getServiceEndpoint();
}
@Override
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
logger.info("Getting database account endpoint from {}", endpoint);
return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return RxDocumentClientImpl.this.getConnectionPolicy();
}
};
}
RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer,
ConsistencyLevel consistencyLevel,
QueryCompatibilityMode queryCompatibilityMode,
UserAgentContainer userAgentContainer,
GlobalEndpointManager globalEndpointManager,
HttpClient httpClient,
ApiType apiType) {
return new RxGatewayStoreModel(
this,
sessionContainer,
consistencyLevel,
queryCompatibilityMode,
userAgentContainer,
globalEndpointManager,
httpClient,
apiType);
}
private HttpClient httpClient() {
HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs)
.withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout())
.withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize())
.withProxy(this.connectionPolicy.getProxy())
.withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout());
if (connectionSharingAcrossClientsEnabled) {
return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig);
} else {
diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig);
return HttpClient.createFixed(httpClientConfig);
}
}
private void createStoreModel(boolean subscribeRntbdStatus) {
StoreClient storeClient = this.storeClientFactory.createStoreClient(this,
this.addressResolver,
this.sessionContainer,
this.gatewayConfigurationReader,
this,
this.useMultipleWriteLocations
);
this.storeModel = new ServerStoreModel(storeClient);
}
@Override
public URI getServiceEndpoint() {
return this.serviceEndpoint;
}
@Override
public URI getWriteEndpoint() {
return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null);
}
@Override
public URI getReadEndpoint() {
return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return this.connectionPolicy;
}
@Override
public boolean isContentResponseOnWriteEnabled() {
return contentResponseOnWriteEnabled;
}
@Override
public ConsistencyLevel getConsistencyLevel() {
return consistencyLevel;
}
@Override
public ClientTelemetry getClientTelemetry() {
return this.clientTelemetry;
}
@Override
public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (database == null) {
throw new IllegalArgumentException("Database");
}
logger.debug("Creating a Database. id: [{}]", database.getId());
validateResource(database);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Reading a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT);
}
private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) {
switch (resourceTypeEnum) {
case Database:
return Paths.DATABASES_ROOT;
case DocumentCollection:
return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT);
case Document:
return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT);
case Offer:
return Paths.OFFERS_ROOT;
case User:
return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT);
case ClientEncryptionKey:
return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
case Permission:
return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT);
case Attachment:
return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT);
case StoredProcedure:
return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
case Trigger:
return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT);
case UserDefinedFunction:
return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
case Conflict:
return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT);
default:
throw new IllegalArgumentException("resource type not supported");
}
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) {
if (options == null) {
return null;
}
return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options);
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) {
if (options == null) {
return null;
}
return options.getOperationContextAndListenerTuple();
}
private <T extends Resource> Flux<FeedResponse<T>> createQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum) {
String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum);
UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getCorrelationActivityId(options);
UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ?
correlationActivityIdOfRequestOptions : Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this,
getOperationContextAndListenerTuple(options));
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> createQueryInternal(
resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId),
invalidPartitionExceptionRetryPolicy);
}
private <T extends Resource> Flux<FeedResponse<T>> createQueryInternal(
String resourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
IDocumentQueryClient queryClient,
UUID activityId) {
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory
.createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery,
options, resourceLink, false, activityId,
Configs.isQueryPlanCachingEnabled(), queryPlanCache);
AtomicBoolean isFirstResponse = new AtomicBoolean(true);
return executionContext.flatMap(iDocumentQueryExecutionContext -> {
QueryInfo queryInfo = null;
if (iDocumentQueryExecutionContext instanceof PipelinedDocumentQueryExecutionContext) {
queryInfo = ((PipelinedDocumentQueryExecutionContext<T>) iDocumentQueryExecutionContext).getQueryInfo();
}
QueryInfo finalQueryInfo = queryInfo;
return iDocumentQueryExecutionContext.executeAsync()
.map(tFeedResponse -> {
if (finalQueryInfo != null) {
if (finalQueryInfo.hasSelectValue()) {
ModelBridgeInternal
.addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo);
}
if (isFirstResponse.compareAndSet(true, false)) {
ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse,
finalQueryInfo.getQueryPlanDiagnosticsContext());
}
}
return tFeedResponse;
});
});
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) {
return queryDatabases(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database);
}
@Override
public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink,
DocumentCollection collection, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink,
DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink,
collection.getId());
validateResource(collection);
String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
});
} catch (Exception e) {
logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Replacing a Collection. id: [{}]", collection.getId());
validateResource(collection);
String path = Utils.joinPath(collection.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
if (resourceResponse.getResource() != null) {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
}
});
} catch (Exception e) {
logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.DELETE)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated));
}
private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated ->
this.getStoreProxy(requestPopulated).processMessage(requestPopulated)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
));
}
@Override
public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class,
Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection);
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection);
}
private static String serializeProcedureParams(List<Object> objectArray) {
String[] stringArray = new String[objectArray.size()];
for (int i = 0; i < objectArray.size(); ++i) {
Object object = objectArray.get(i);
if (object instanceof JsonSerializable) {
stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object);
} else {
try {
stringArray[i] = mapper.writeValueAsString(object);
} catch (IOException e) {
throw new IllegalArgumentException("Can't serialize the object into the json string", e);
}
}
}
return String.format("[%s]", StringUtils.join(stringArray, ","));
}
private static void validateResource(Resource resource) {
if (!StringUtils.isEmpty(resource.getId())) {
if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 ||
resource.getId().indexOf('?') != -1 || resource.getId().indexOf('
throw new IllegalArgumentException("Id contains illegal chars.");
}
if (resource.getId().endsWith(" ")) {
throw new IllegalArgumentException("Id ends with a space.");
}
}
}
private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) {
Map<String, String> headers = new HashMap<>();
if (this.useMultipleWriteLocations) {
headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString());
}
if (consistencyLevel != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString());
}
if (options == null) {
if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
return headers;
}
Map<String, String> customOptions = options.getHeaders();
if (customOptions != null) {
headers.putAll(customOptions);
}
boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled;
if (options.isContentResponseOnWriteEnabled() != null) {
contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled();
}
if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
if (options.getIfMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag());
}
if(options.getIfNoneMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag());
}
if (options.getConsistencyLevel() != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString());
}
if (options.getIndexingDirective() != null) {
headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString());
}
if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) {
String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude);
}
if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) {
String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude);
}
if (!Strings.isNullOrEmpty(options.getSessionToken())) {
headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken());
}
if (options.getResourceTokenExpirySeconds() != null) {
headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY,
String.valueOf(options.getResourceTokenExpirySeconds()));
}
if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString());
} else if (options.getOfferType() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType());
}
if (options.getOfferThroughput() == null) {
if (options.getThroughputProperties() != null) {
Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties());
final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings();
OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null;
if (offerAutoscaleSettings != null) {
autoscaleAutoUpgradeProperties
= offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties();
}
if (offer.hasOfferThroughput() &&
(offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 ||
autoscaleAutoUpgradeProperties != null &&
autoscaleAutoUpgradeProperties
.getAutoscaleThroughputProperties()
.getIncrementPercent() >= 0)) {
throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with "
+ "fixed offer");
}
if (offer.hasOfferThroughput()) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput()));
} else if (offer.getOfferAutoScaleSettings() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS,
ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings()));
}
}
}
if (options.isQuotaInfoEnabled()) {
headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true));
}
if (options.isScriptLoggingEnabled()) {
headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true));
}
if (options.getDedicatedGatewayRequestOptions() != null &&
options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) {
headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS,
String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions())));
}
return headers;
}
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return this.resetSessionTokenRetryPolicy;
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Document document,
RequestOptions options) {
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs
.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object document,
RequestOptions options,
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) {
return collectionObs.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private void addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object objectDoc, RequestOptions options,
DocumentCollection collection) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
PartitionKeyInternal partitionKeyInternal = null;
if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else if (options != null && options.getPartitionKey() != null) {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey());
} else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) {
partitionKeyInternal = PartitionKeyInternal.getEmpty();
} else if (contentAsByteBuffer != null || objectDoc != null) {
InternalObjectNode internalObjectNode;
if (objectDoc instanceof InternalObjectNode) {
internalObjectNode = (InternalObjectNode) objectDoc;
} else if (objectDoc instanceof ObjectNode) {
internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc);
} else if (contentAsByteBuffer != null) {
contentAsByteBuffer.rewind();
internalObjectNode = new InternalObjectNode(contentAsByteBuffer);
} else {
throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null");
}
Instant serializationStartTime = Instant.now();
partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTime,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION
);
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
} else {
throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation.");
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
}
public static PartitionKeyInternal extractPartitionKeyValueFromDocument(
InternalObjectNode document,
PartitionKeyDefinition partitionKeyDefinition) {
if (partitionKeyDefinition != null) {
switch (partitionKeyDefinition.getKind()) {
case HASH:
String path = partitionKeyDefinition.getPaths().iterator().next();
List<String> parts = PathParser.getPathParts(path);
if (parts.size() >= 1) {
Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts);
if (value == null || value.getClass() == ObjectNode.class) {
value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
}
if (value instanceof PartitionKeyInternal) {
return (PartitionKeyInternal) value;
} else {
return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false);
}
}
break;
case MULTI_HASH:
Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()];
for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){
String partitionPath = partitionKeyDefinition.getPaths().get(pathIter);
List<String> partitionPathParts = PathParser.getPathParts(partitionPath);
partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts);
}
return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false);
default:
throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind());
}
}
return null;
}
private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
Object document,
RequestOptions options,
boolean disableAutomaticIdGeneration,
OperationType operationType) {
if (StringUtils.isEmpty(documentCollectionLink)) {
throw new IllegalArgumentException("documentCollectionLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Document, path, requestHeaders, options, content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return addPartitionKeyInformation(request, content, document, options, collectionObs);
}
private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink");
checkNotNull(serverBatchRequest, "expected non null serverBatchRequest");
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody()));
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Batch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> {
addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v);
return request;
});
}
private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request,
ServerBatchRequest serverBatchRequest,
DocumentCollection collection) {
if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) {
PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue();
PartitionKeyInternal partitionKeyInternal;
if (partitionKey.equals(PartitionKey.NONE)) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey);
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
} else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) {
request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId()));
} else {
throw new UnsupportedOperationException("Unknown Server request.");
}
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString());
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch()));
request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError()));
request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size());
return request;
}
private Mono<RxDocumentServiceRequest> populateHeaders(RxDocumentServiceRequest request, RequestVerb httpMethod) {
request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123());
if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null
|| this.cosmosAuthorizationTokenResolver != null || this.credential != null) {
String resourceName = request.getResourceAddress();
String authorization = this.getUserAuthorizationToken(
resourceName, request.getResourceType(), httpMethod, request.getHeaders(),
AuthorizationTokenType.PrimaryMasterKey, request.properties);
try {
authorization = URLEncoder.encode(authorization, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Failed to encode authtoken.", e);
}
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
}
if (this.apiType != null) {
request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString());
}
if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod))
&& !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
}
if (RequestVerb.PATCH.equals(httpMethod) &&
!request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH);
}
if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) {
request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
}
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
if (this.requiresFeedRangeFiltering(request)) {
return request.getFeedRange()
.populateFeedRangeFilteringHeaders(
this.getPartitionKeyRangeCache(),
request,
this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request))
.flatMap(this::populateAuthorizationHeader);
}
return this.populateAuthorizationHeader(request);
}
private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) {
if (request.getResourceType() != ResourceType.Document &&
request.getResourceType() != ResourceType.Conflict) {
return false;
}
switch (request.getOperationType()) {
case ReadFeed:
case Query:
case SqlQuery:
return request.getFeedRange() != null;
default:
return false;
}
}
@Override
public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) {
if (request == null) {
throw new IllegalArgumentException("request");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return request;
});
} else {
return Mono.just(request);
}
}
@Override
public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) {
if (httpHeaders == null) {
throw new IllegalArgumentException("httpHeaders");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return httpHeaders;
});
}
return Mono.just(httpHeaders);
}
@Override
public AuthorizationTokenType getAuthorizationTokenType() {
return this.authorizationTokenType;
}
@Override
public String getUserAuthorizationToken(String resourceName,
ResourceType resourceType,
RequestVerb requestVerb,
Map<String, String> headers,
AuthorizationTokenType tokenType,
Map<String, Object> properties) {
if (this.cosmosAuthorizationTokenResolver != null) {
return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(),
properties != null ? Collections.unmodifiableMap(properties) : null);
} else if (credential != null) {
return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName,
resourceType, headers);
} else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) {
return masterKeyOrResourceToken;
} else {
assert resourceTokensMap != null;
if(resourceType.equals(ResourceType.DatabaseAccount)) {
return this.firstResourceTokenFromPermissionFeed;
}
return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers);
}
}
private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) {
CosmosResourceType cosmosResourceType =
ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString());
if (cosmosResourceType == null) {
return CosmosResourceType.SYSTEM;
}
return cosmosResourceType;
}
void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) {
this.sessionContainer.setSessionToken(request, response.getResponseHeaders());
}
private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
Map<String, String> headers = requestPopulated.getHeaders();
assert (headers != null);
headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true");
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
);
});
}
private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.PUT)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PATCH);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(request).processMessage(request);
}
@Override
public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) {
try {
logger.debug("Creating a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Create);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance);
}
private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Upsert);
Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = Utils.getCollectionName(documentLink);
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Document typedDocument = documentFromObject(document, mapper);
return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = document.getSelfLink();
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (document == null) {
throw new IllegalArgumentException("document");
}
return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a database due to [{}]", e.getMessage());
return Mono.error(e);
}
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink,
Document document,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
if (document == null) {
throw new IllegalArgumentException("document");
}
logger.debug("Replacing a Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = serializeJsonToByteBuffer(document);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs);
return requestObs.flatMap(req -> replace(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> patchDocument(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink");
checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations");
logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options));
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Patch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(
request,
null,
null,
options,
collectionObs);
return requestObs.flatMap(req -> patch(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy);
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Deleting a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs);
return requestObs.flatMap(req -> this
.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> this
.deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting documents due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Reading a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> {
return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Document>> readDocuments(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return queryDocuments(collectionLink, "SELECT * FROM r", options);
}
@Override
public <T> Mono<FeedResponse<T>> readMany(
List<CosmosItemIdentity> itemIdentityList,
String collectionLink,
CosmosQueryRequestOptions options,
Class<T> klass) {
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink, null
);
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request);
return collectionObs
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache
.tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null);
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap =
new HashMap<>();
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
itemIdentityList
.forEach(itemIdentity -> {
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(
itemIdentity.getPartitionKey()),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
if (partitionRangeItemKeyMap.get(range) == null) {
List<CosmosItemIdentity> list = new ArrayList<>();
list.add(itemIdentity);
partitionRangeItemKeyMap.put(range, list);
} else {
List<CosmosItemIdentity> pairs =
partitionRangeItemKeyMap.get(range);
pairs.add(itemIdentity);
partitionRangeItemKeyMap.put(range, pairs);
}
});
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap;
rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap,
collection.getPartitionKey());
return createReadManyQuery(
resourceLink,
new SqlQuerySpec(DUMMY_SQL_QUERY),
options,
Document.class,
ResourceType.Document,
collection,
Collections.unmodifiableMap(rangeQueryMap))
.collectList()
.map(feedList -> {
List<T> finalList = new ArrayList<>();
HashMap<String, String> headers = new HashMap<>();
ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>();
double requestCharge = 0;
for (FeedResponse<Document> page : feedList) {
ConcurrentMap<String, QueryMetrics> pageQueryMetrics =
ModelBridgeInternal.queryMetrics(page);
if (pageQueryMetrics != null) {
pageQueryMetrics.forEach(
aggregatedQueryMetrics::putIfAbsent);
}
requestCharge += page.getRequestCharge();
finalList.addAll(page.getResults().stream().map(document ->
ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList()));
}
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double
.toString(requestCharge));
FeedResponse<T> frp = BridgeInternal
.createFeedResponse(finalList, headers);
return frp;
});
});
}
);
}
private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap(
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap,
PartitionKeyDefinition partitionKeyDefinition) {
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>();
String partitionKeySelector = createPkSelector(partitionKeyDefinition);
for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) {
SqlQuerySpec sqlQuerySpec;
if (partitionKeySelector.equals("[\"id\"]")) {
sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector);
} else {
sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector);
}
rangeQueryMap.put(entry.getKey(), sqlQuerySpec);
}
return rangeQueryMap;
}
private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(
List<CosmosItemIdentity> idPartitionKeyPairList,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( ");
for (int i = 0; i < idPartitionKeyPairList.size(); i++) {
CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i);
String idValue = itemIdentity.getId();
String idParamName = "@param" + i;
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
if (!Objects.equals(idValue, pkValue)) {
continue;
}
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append(idParamName);
if (i < idPartitionKeyPairList.size() - 1) {
queryStringBuilder.append(", ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE ( ");
for (int i = 0; i < itemIdentities.size(); i++) {
CosmosItemIdentity itemIdentity = itemIdentities.get(i);
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
String pkParamName = "@param" + (2 * i);
parameters.add(new SqlParameter(pkParamName, pkValue));
String idValue = itemIdentity.getId();
String idParamName = "@param" + (2 * i + 1);
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append("(");
queryStringBuilder.append("c.id = ");
queryStringBuilder.append(idParamName);
queryStringBuilder.append(" AND ");
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
queryStringBuilder.append(" )");
if (i < itemIdentities.size() - 1) {
queryStringBuilder.append(" OR ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) {
return partitionKeyDefinition.getPaths()
.stream()
.map(pathPart -> StringUtils.substring(pathPart, 1))
.map(pathPart -> StringUtils.replace(pathPart, "\"", "\\"))
.map(part -> "[\"" + part + "\"]")
.collect(Collectors.joining());
}
private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
DocumentCollection collection,
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) {
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(),
sqlQuery,
rangeQueryMap,
options,
collection.getResourceId(),
parentResourceLink,
activityId,
klass,
resourceTypeEnum);
return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync);
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, String query, CosmosQueryRequestOptions options) {
return queryDocuments(collectionLink, new SqlQuerySpec(query), options);
}
private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return new IDocumentQueryClient () {
@Override
public RxCollectionCache getCollectionCache() {
return RxDocumentClientImpl.this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return RxDocumentClientImpl.this.partitionKeyRangeCache;
}
@Override
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy;
}
@Override
public ConsistencyLevel getDefaultConsistencyLevelAsync() {
return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel();
}
@Override
public ConsistencyLevel getDesiredConsistencyLevelAsync() {
return RxDocumentClientImpl.this.consistencyLevel;
}
@Override
public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) {
if (operationContextAndListenerTuple == null) {
return RxDocumentClientImpl.this.query(request).single();
} else {
final OperationListener listener =
operationContextAndListenerTuple.getOperationListener();
final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext();
request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId());
listener.requestListener(operationContext, request);
return RxDocumentClientImpl.this.query(request).single().doOnNext(
response -> listener.responseListener(operationContext, response)
).doOnError(
ex -> listener.exceptionListener(operationContext, ex)
);
}
}
@Override
public QueryCompatibilityMode getQueryCompatibilityMode() {
return QueryCompatibilityMode.Default;
}
@Override
public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) {
return null;
}
};
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
SqlQuerySpecLogger.getInstance().logQuery(querySpec);
return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document);
}
@Override
public Flux<FeedResponse<Document>> queryDocumentChangeFeed(
final DocumentCollection collection,
final CosmosChangeFeedRequestOptions changeFeedOptions) {
checkNotNull(collection, "Argument 'collection' must not be null.");
ChangeFeedQueryImpl<Document> changeFeedQueryImpl = new ChangeFeedQueryImpl<>(
this,
ResourceType.Document,
Document.class,
collection.getAltLink(),
collection.getResourceId(),
changeFeedOptions);
return changeFeedQueryImpl.executeAsync();
}
@Override
public Flux<FeedResponse<Document>> readAllDocuments(
String collectionLink,
PartitionKey partitionKey,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (partitionKey == null) {
throw new IllegalArgumentException("partitionKey");
}
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null
);
Flux<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request).flux();
return collectionObs.flatMap(documentCollectionResourceResponse -> {
DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
String pkSelector = createPkSelector(pkDefinition);
SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector);
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
final CosmosQueryRequestOptions effectiveOptions =
ModelBridgeInternal.createQueryRequestOptions(options);
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> {
Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache
.tryLookupAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null).flux();
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(partitionKey),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
return createQueryInternal(
resourceLink,
querySpec,
ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()),
Document.class,
ResourceType.Document,
queryClient,
activityId);
});
},
invalidPartitionExceptionRetryPolicy);
});
}
@Override
public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() {
return queryPlanCache;
}
@Override
public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class,
Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT));
}
private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
validateResource(storedProcedure);
String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType,
ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
return request;
}
private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (udf == null) {
throw new IllegalArgumentException("udf");
}
validateResource(udf);
String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Create);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId());
RxDocumentClientImpl.validateResource(storedProcedure);
String path = Utils.joinPath(storedProcedure.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class,
Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
List<Object> procedureParams) {
return this.executeStoredProcedure(storedProcedureLink, null, procedureParams);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy);
}
@Override
public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy);
}
private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) {
try {
logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript);
requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ExecuteJavaScript,
ResourceType.StoredProcedure, path,
procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "",
requestHeaders, options);
if (retryPolicy != null) {
retryPolicy.onBeforeSendRequest(request);
}
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options))
.map(response -> {
this.captureSessionToken(request, response);
return toStoredProcedureResponse(response);
}));
} catch (Exception e) {
logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
DocumentClientRetryPolicy requestRetryPolicy,
boolean disableAutomaticIdGeneration) {
try {
logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size());
Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true));
} catch (Exception ex) {
logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex);
return Mono.error(ex);
}
}
@Override
public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path,
trigger, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId());
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(trigger.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Trigger, Trigger.class,
Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryTriggers(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger);
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (udf == null) {
throw new IllegalArgumentException("udf");
}
logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId());
validateResource(udf);
String path = Utils.joinPath(udf.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class,
Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
String query, CosmosQueryRequestOptions options) {
return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction);
}
@Override
public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Conflict, Conflict.class,
Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryConflicts(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict);
}
@Override
public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (user == null) {
throw new IllegalArgumentException("user");
}
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.User, path, user, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (user == null) {
throw new IllegalArgumentException("user");
}
logger.debug("Replacing a User. user id [{}]", user.getId());
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(user.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.User, path, user, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Deleting a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Reading a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.User, User.class,
Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) {
return queryUsers(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User);
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(clientEncryptionKeyLink)) {
throw new IllegalArgumentException("clientEncryptionKeyLink");
}
logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink);
String path = Utils.joinPath(clientEncryptionKeyLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink,
ClientEncryptionKey clientEncryptionKey, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId());
RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey,
String nameBasedLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey,
nameBasedLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId());
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(nameBasedLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey,
OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders,
options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class,
Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey);
}
@Override
public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy());
}
private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
if (permission == null) {
throw new IllegalArgumentException("permission");
}
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Permission, path, permission, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (permission == null) {
throw new IllegalArgumentException("permission");
}
logger.debug("Replacing a Permission. permission id [{}]", permission.getId());
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(permission.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Reading a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
return readFeed(options, ResourceType.Permission, Permission.class,
Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query,
CosmosQueryRequestOptions options) {
return queryPermissions(userLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission);
}
@Override
public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
if (offer == null) {
throw new IllegalArgumentException("offer");
}
logger.debug("Replacing an Offer. offer id [{}]", offer.getId());
RxDocumentClientImpl.validateResource(offer);
String path = Utils.joinPath(offer.getSelfLink(), null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace,
ResourceType.Offer, path, offer, null, null);
return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Offer>> readOffer(String offerLink) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(offerLink)) {
throw new IllegalArgumentException("offerLink");
}
logger.debug("Reading an Offer. offerLink [{}]", offerLink);
String path = Utils.joinPath(offerLink, null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Offer, Offer.class,
Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null));
}
private <T extends Resource> Flux<FeedResponse<T>> readFeed(CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options);
int maxPageSize = maxItemCount != null ? maxItemCount : -1;
final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options;
DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> {
Map<String, String> requestHeaders = new HashMap<>();
if (continuationToken != null) {
requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken);
}
requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize));
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions);
retryPolicy.onBeforeSendRequest(request);
return request;
};
Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper
.inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)),
retryPolicy);
return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, maxPageSize);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) {
return queryOffers(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer);
}
@Override
public Mono<DatabaseAccount> getDatabaseAccount() {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy),
documentClientRetryPolicy);
}
@Override
public DatabaseAccount getLatestDatabaseAccount() {
return this.globalEndpointManager.getLatestDatabaseAccount();
}
private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Getting Database Account");
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read,
ResourceType.DatabaseAccount, "",
(HashMap<String, String>) null,
null);
return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount);
} catch (Exception e) {
logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Object getSession() {
return this.sessionContainer;
}
public void setSession(Object sessionContainer) {
this.sessionContainer = (SessionContainer) sessionContainer;
}
@Override
public RxClientCollectionCache getCollectionCache() {
return this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return partitionKeyRangeCache;
}
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
return Flux.defer(() -> {
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null);
return this.populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
requestPopulated.setEndpointOverride(endpoint);
return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> {
String message = String.format("Failed to retrieve database account information. %s",
e.getCause() != null
? e.getCause().toString()
: e.toString());
logger.warn(message);
}).map(rsp -> rsp.getResource(DatabaseAccount.class))
.doOnNext(databaseAccount ->
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled()
&& BridgeInternal.isEnableMultipleWriteLocations(databaseAccount));
});
});
}
/**
* Certain requests must be routed through gateway even when the client connectivity mode is direct.
*
* @param request
* @return RxStoreModel
*/
private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) {
if (request.UseGatewayMode) {
return this.gatewayProxy;
}
ResourceType resourceType = request.getResourceType();
OperationType operationType = request.getOperationType();
if (resourceType == ResourceType.Offer ||
resourceType == ResourceType.ClientEncryptionKey ||
resourceType.isScript() && operationType != OperationType.ExecuteJavaScript ||
resourceType == ResourceType.PartitionKeyRange ||
resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) {
return this.gatewayProxy;
}
if (operationType == OperationType.Create
|| operationType == OperationType.Upsert) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection ||
resourceType == ResourceType.Permission) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Delete) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Replace) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Read) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else {
if ((operationType == OperationType.Query ||
operationType == OperationType.SqlQuery ||
operationType == OperationType.ReadFeed) &&
Utils.isCollectionChild(request.getResourceType())) {
if (request.getPartitionKeyRangeIdentity() == null &&
request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) {
return this.gatewayProxy;
}
}
return this.storeModel;
}
}
@Override
public void close() {
logger.info("Attempting to close client {}", this.clientId);
if (!closed.getAndSet(true)) {
activeClientsCnt.decrementAndGet();
logger.info("Shutting down ...");
logger.info("Closing Global Endpoint Manager ...");
LifeCycleUtils.closeQuietly(this.globalEndpointManager);
logger.info("Closing StoreClientFactory ...");
LifeCycleUtils.closeQuietly(this.storeClientFactory);
logger.info("Shutting down reactorHttpClient ...");
LifeCycleUtils.closeQuietly(this.reactorHttpClient);
logger.info("Shutting down CpuMonitor ...");
CpuMemoryMonitor.unregister(this);
if (this.throughputControlEnabled.get()) {
logger.info("Closing ThroughputControlStore ...");
this.throughputControlStore.close();
}
logger.info("Shutting down completed.");
} else {
logger.warn("Already shutdown!");
}
}
@Override
public ItemDeserializer getItemDeserializer() {
return this.itemDeserializer;
}
@Override
public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group can not be null");
if (this.throughputControlEnabled.compareAndSet(false, true)) {
this.throughputControlStore =
new ThroughputControlStore(
this.collectionCache,
this.connectionPolicy.getConnectionMode(),
this.partitionKeyRangeCache);
this.storeModel.enableThroughputControl(throughputControlStore);
}
this.throughputControlStore.enableThroughputControlGroup(group);
}
private static SqlQuerySpec createLogicalPartitionScanQuerySpec(
PartitionKey partitionKey,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE");
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey);
String pkParamName = "@pkValue";
parameters.add(new SqlParameter(pkParamName, pkValue));
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
@Override
public Mono<List<FeedRange>> getFeedRanges(String collectionLink) {
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
collectionLink,
new HashMap<>());
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null);
invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request);
return ObservableHelper.inlineIfPossibleAsObs(
() -> getFeedRangesInternal(request, collectionLink),
invalidPartitionExceptionRetryPolicy);
}
private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) {
logger.debug("getFeedRange collectionLink=[{}]", collectionLink);
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null,
request);
return collectionObs.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache
.tryGetOverlappingRangesAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null);
return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request));
});
}
private static List<FeedRange> toFeedRanges(
Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) {
final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v;
if (partitionKeyRangeList == null) {
request.forceNameCacheRefresh = true;
throw new InvalidPartitionException();
}
List<FeedRange> feedRanges = new ArrayList<>();
partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange)));
return feedRanges;
}
private static FeedRange toFeedRange(PartitionKeyRange pkRange) {
return new FeedRangeEpkImpl(pkRange.toRange());
}
} |
I think I am not able to communicate my thought clearly , and as I mentioned previously I am not saying clientId is a replacement of machineId, but thats fine , I can take this change later | public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) {
try {
this.httpClientInterceptor = httpClientInterceptor;
if (httpClientInterceptor != null) {
this.reactorHttpClient = httpClientInterceptor.apply(httpClient());
}
this.gatewayProxy = createRxGatewayProxy(this.sessionContainer,
this.consistencyLevel,
this.queryCompatibilityMode,
this.userAgentContainer,
this.globalEndpointManager,
this.reactorHttpClient,
this.apiType);
this.globalEndpointManager.init();
this.initializeGatewayConfigurationReader();
if (metadataCachesSnapshot != null) {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy,
metadataCachesSnapshot.getCollectionInfoByNameCache(),
metadataCachesSnapshot.getCollectionInfoByIdCache()
);
} else {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy);
}
this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy);
this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this,
collectionCache);
updateGatewayProxy();
clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(),
ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(),
connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(),
null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions());
clientTelemetry.init();
if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) {
this.storeModel = this.gatewayProxy;
} else {
this.initializeDirectConnectivity();
}
this.retryPolicy.setRxCollectionCache(this.collectionCache);
} catch (Exception e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
} | clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(), | public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) {
try {
this.httpClientInterceptor = httpClientInterceptor;
if (httpClientInterceptor != null) {
this.reactorHttpClient = httpClientInterceptor.apply(httpClient());
}
this.gatewayProxy = createRxGatewayProxy(this.sessionContainer,
this.consistencyLevel,
this.queryCompatibilityMode,
this.userAgentContainer,
this.globalEndpointManager,
this.reactorHttpClient,
this.apiType);
this.globalEndpointManager.init();
this.initializeGatewayConfigurationReader();
if (metadataCachesSnapshot != null) {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy,
metadataCachesSnapshot.getCollectionInfoByNameCache(),
metadataCachesSnapshot.getCollectionInfoByIdCache()
);
} else {
this.collectionCache = new RxClientCollectionCache(this,
this.sessionContainer,
this.gatewayProxy,
this,
this.retryPolicy);
}
this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy);
this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this,
collectionCache);
updateGatewayProxy();
clientTelemetry = new ClientTelemetry(this, null, UUID.randomUUID().toString(),
ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(),
connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(),
null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this, this.connectionPolicy.getPreferredRegions());
clientTelemetry.init();
if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) {
this.storeModel = this.gatewayProxy;
} else {
this.initializeDirectConnectivity();
}
this.retryPolicy.setRxCollectionCache(this.collectionCache);
} catch (Exception e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
} | class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener,
DiagnosticsClientContext {
private static final String tempMachineId = "uuid:" + UUID.randomUUID();
private static final AtomicInteger activeClientsCnt = new AtomicInteger(0);
private static final AtomicInteger clientIdGenerator = new AtomicInteger(0);
private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>(
PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey,
PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false);
private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " +
"ParallelDocumentQueryExecutioncontext, but not used";
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper();
private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer();
private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class);
private final String masterKeyOrResourceToken;
private final URI serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel consistencyLevel;
private final BaseAuthorizationTokenProvider authorizationTokenProvider;
private final UserAgentContainer userAgentContainer;
private final boolean hasAuthKeyResourceToken;
private final Configs configs;
private final boolean connectionSharingAcrossClientsEnabled;
private AzureKeyCredential credential;
private final TokenCredential tokenCredential;
private String[] tokenCredentialScopes;
private SimpleTokenCache tokenCredentialCache;
private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver;
AuthorizationTokenType authorizationTokenType;
private SessionContainer sessionContainer;
private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY;
private RxClientCollectionCache collectionCache;
private RxStoreModel gatewayProxy;
private RxStoreModel storeModel;
private GlobalAddressResolver addressResolver;
private RxPartitionKeyRangeCache partitionKeyRangeCache;
private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap;
private final boolean contentResponseOnWriteEnabled;
private Map<String, PartitionedQueryExecutionInfo> queryPlanCache;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final int clientId;
private ClientTelemetry clientTelemetry;
private ApiType apiType;
private IRetryPolicyFactory resetSessionTokenRetryPolicy;
/**
* Compatibility mode: Allows to specify compatibility mode used by client when
* making query requests. Should be removed when application/sql is no longer
* supported.
*/
private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default;
private final GlobalEndpointManager globalEndpointManager;
private final RetryPolicy retryPolicy;
private HttpClient reactorHttpClient;
private Function<HttpClient, HttpClient> httpClientInterceptor;
private volatile boolean useMultipleWriteLocations;
private StoreClientFactory storeClientFactory;
private GatewayServiceConfigurationReader gatewayConfigurationReader;
private final DiagnosticsClientConfig diagnosticsClientConfig;
private final AtomicBoolean throughputControlEnabled;
private ThroughputControlStore throughputControlStore;
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
private RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
if (permissionFeed != null && permissionFeed.size() > 0) {
this.resourceTokensMap = new HashMap<>();
for (Permission permission : permissionFeed) {
String[] segments = StringUtils.split(permission.getResourceLink(),
Constants.Properties.PATH_SEPARATOR.charAt(0));
if (segments.length <= 0) {
throw new IllegalArgumentException("resourceLink");
}
List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null;
PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false);
if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) {
throw new IllegalArgumentException(permission.getResourceLink());
}
partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName);
if (partitionKeyAndResourceTokenPairs == null) {
partitionKeyAndResourceTokenPairs = new ArrayList<>();
this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs);
}
PartitionKey partitionKey = permission.getResourcePartitionKey();
partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair(
partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty,
permission.getToken()));
logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]",
pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken());
}
if(this.resourceTokensMap.isEmpty()) {
throw new IllegalArgumentException("permissionFeed");
}
String firstToken = permissionFeed.get(0).getToken();
if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) {
this.firstResourceTokenFromPermissionFeed = firstToken;
}
}
}
RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
activeClientsCnt.incrementAndGet();
this.clientId = clientIdGenerator.incrementAndGet();
this.diagnosticsClientConfig = new DiagnosticsClientConfig();
this.diagnosticsClientConfig.withClientId(this.clientId);
this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt);
this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled);
this.diagnosticsClientConfig.withConsistency(consistencyLevel);
this.throughputControlEnabled = new AtomicBoolean(false);
logger.info(
"Initializing DocumentClient [{}] with"
+ " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]",
this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol());
try {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
this.configs = configs;
this.masterKeyOrResourceToken = masterKeyOrResourceToken;
this.serviceEndpoint = serviceEndpoint;
this.credential = credential;
this.tokenCredential = tokenCredential;
this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled;
this.authorizationTokenType = AuthorizationTokenType.Invalid;
if (this.credential != null) {
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.authorizationTokenProvider = null;
hasAuthKeyResourceToken = true;
this.authorizationTokenType = AuthorizationTokenType.ResourceToken;
} else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken);
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else {
hasAuthKeyResourceToken = false;
this.authorizationTokenProvider = null;
if (tokenCredential != null) {
this.tokenCredentialScopes = new String[] {
serviceEndpoint.getScheme() + ":
};
this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential
.getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes)));
this.authorizationTokenType = AuthorizationTokenType.AadToken;
}
}
if (connectionPolicy != null) {
this.connectionPolicy = connectionPolicy;
} else {
this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig());
}
this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode());
this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled());
this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled());
this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions());
this.diagnosticsClientConfig.withMachineId(tempMachineId);
boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled);
this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing);
this.consistencyLevel = consistencyLevel;
this.userAgentContainer = new UserAgentContainer();
String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix();
if (userAgentSuffix != null && userAgentSuffix.length() > 0) {
userAgentContainer.setSuffix(userAgentSuffix);
}
this.httpClientInterceptor = null;
this.reactorHttpClient = httpClient();
this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs);
this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy);
this.resetSessionTokenRetryPolicy = retryPolicy;
CpuMemoryMonitor.register(this);
this.queryPlanCache = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE));
this.apiType = apiType;
} catch (RuntimeException e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
}
@Override
public DiagnosticsClientConfig getConfig() {
return diagnosticsClientConfig;
}
@Override
public CosmosDiagnostics createDiagnostics() {
return BridgeInternal.createCosmosDiagnostics(this, this.globalEndpointManager);
}
private void initializeGatewayConfigurationReader() {
this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager);
DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount();
if (databaseAccount == null) {
logger.error("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
throw new RuntimeException("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
}
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount);
}
private void updateGatewayProxy() {
((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader);
((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache);
((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache);
((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations);
}
public void serialize(CosmosClientMetadataCachesSnapshot state) {
RxCollectionCache.serialize(state, this.collectionCache);
}
private void initializeDirectConnectivity() {
this.addressResolver = new GlobalAddressResolver(this,
this.reactorHttpClient,
this.globalEndpointManager,
this.configs.getProtocol(),
this,
this.collectionCache,
this.partitionKeyRangeCache,
userAgentContainer,
null,
this.connectionPolicy,
this.apiType);
this.storeClientFactory = new StoreClientFactory(
this.addressResolver,
this.diagnosticsClientConfig,
this.configs,
this.connectionPolicy,
this.userAgentContainer,
this.connectionSharingAcrossClientsEnabled,
this.clientTelemetry
);
this.createStoreModel(true);
}
DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() {
return new DatabaseAccountManagerInternal() {
@Override
public URI getServiceEndpoint() {
return RxDocumentClientImpl.this.getServiceEndpoint();
}
@Override
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
logger.info("Getting database account endpoint from {}", endpoint);
return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return RxDocumentClientImpl.this.getConnectionPolicy();
}
};
}
RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer,
ConsistencyLevel consistencyLevel,
QueryCompatibilityMode queryCompatibilityMode,
UserAgentContainer userAgentContainer,
GlobalEndpointManager globalEndpointManager,
HttpClient httpClient,
ApiType apiType) {
return new RxGatewayStoreModel(
this,
sessionContainer,
consistencyLevel,
queryCompatibilityMode,
userAgentContainer,
globalEndpointManager,
httpClient,
apiType);
}
private HttpClient httpClient() {
HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs)
.withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout())
.withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize())
.withProxy(this.connectionPolicy.getProxy())
.withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout());
if (connectionSharingAcrossClientsEnabled) {
return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig);
} else {
diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig);
return HttpClient.createFixed(httpClientConfig);
}
}
private void createStoreModel(boolean subscribeRntbdStatus) {
StoreClient storeClient = this.storeClientFactory.createStoreClient(this,
this.addressResolver,
this.sessionContainer,
this.gatewayConfigurationReader,
this,
this.useMultipleWriteLocations
);
this.storeModel = new ServerStoreModel(storeClient);
}
@Override
public URI getServiceEndpoint() {
return this.serviceEndpoint;
}
@Override
public URI getWriteEndpoint() {
return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null);
}
@Override
public URI getReadEndpoint() {
return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return this.connectionPolicy;
}
@Override
public boolean isContentResponseOnWriteEnabled() {
return contentResponseOnWriteEnabled;
}
@Override
public ConsistencyLevel getConsistencyLevel() {
return consistencyLevel;
}
@Override
public ClientTelemetry getClientTelemetry() {
return this.clientTelemetry;
}
@Override
public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (database == null) {
throw new IllegalArgumentException("Database");
}
logger.debug("Creating a Database. id: [{}]", database.getId());
validateResource(database);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Reading a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT);
}
private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) {
switch (resourceTypeEnum) {
case Database:
return Paths.DATABASES_ROOT;
case DocumentCollection:
return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT);
case Document:
return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT);
case Offer:
return Paths.OFFERS_ROOT;
case User:
return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT);
case ClientEncryptionKey:
return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
case Permission:
return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT);
case Attachment:
return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT);
case StoredProcedure:
return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
case Trigger:
return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT);
case UserDefinedFunction:
return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
case Conflict:
return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT);
default:
throw new IllegalArgumentException("resource type not supported");
}
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) {
if (options == null) {
return null;
}
return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options);
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) {
if (options == null) {
return null;
}
return options.getOperationContextAndListenerTuple();
}
private <T extends Resource> Flux<FeedResponse<T>> createQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum) {
String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum);
UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getCorrelationActivityId(options);
UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ?
correlationActivityIdOfRequestOptions : Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this,
getOperationContextAndListenerTuple(options));
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> createQueryInternal(
resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId),
invalidPartitionExceptionRetryPolicy);
}
private <T extends Resource> Flux<FeedResponse<T>> createQueryInternal(
String resourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
IDocumentQueryClient queryClient,
UUID activityId) {
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory
.createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery,
options, resourceLink, false, activityId,
Configs.isQueryPlanCachingEnabled(), queryPlanCache);
AtomicBoolean isFirstResponse = new AtomicBoolean(true);
return executionContext.flatMap(iDocumentQueryExecutionContext -> {
QueryInfo queryInfo = null;
if (iDocumentQueryExecutionContext instanceof PipelinedDocumentQueryExecutionContext) {
queryInfo = ((PipelinedDocumentQueryExecutionContext<T>) iDocumentQueryExecutionContext).getQueryInfo();
}
QueryInfo finalQueryInfo = queryInfo;
return iDocumentQueryExecutionContext.executeAsync()
.map(tFeedResponse -> {
if (finalQueryInfo != null) {
if (finalQueryInfo.hasSelectValue()) {
ModelBridgeInternal
.addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo);
}
if (isFirstResponse.compareAndSet(true, false)) {
ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse,
finalQueryInfo.getQueryPlanDiagnosticsContext());
}
}
return tFeedResponse;
});
});
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) {
return queryDatabases(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database);
}
@Override
public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink,
DocumentCollection collection, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink,
DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink,
collection.getId());
validateResource(collection);
String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
});
} catch (Exception e) {
logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Replacing a Collection. id: [{}]", collection.getId());
validateResource(collection);
String path = Utils.joinPath(collection.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
if (resourceResponse.getResource() != null) {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
}
});
} catch (Exception e) {
logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.DELETE)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated));
}
private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated ->
this.getStoreProxy(requestPopulated).processMessage(requestPopulated)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
));
}
@Override
public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class,
Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection);
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection);
}
private static String serializeProcedureParams(List<Object> objectArray) {
String[] stringArray = new String[objectArray.size()];
for (int i = 0; i < objectArray.size(); ++i) {
Object object = objectArray.get(i);
if (object instanceof JsonSerializable) {
stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object);
} else {
try {
stringArray[i] = mapper.writeValueAsString(object);
} catch (IOException e) {
throw new IllegalArgumentException("Can't serialize the object into the json string", e);
}
}
}
return String.format("[%s]", StringUtils.join(stringArray, ","));
}
private static void validateResource(Resource resource) {
if (!StringUtils.isEmpty(resource.getId())) {
if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 ||
resource.getId().indexOf('?') != -1 || resource.getId().indexOf('
throw new IllegalArgumentException("Id contains illegal chars.");
}
if (resource.getId().endsWith(" ")) {
throw new IllegalArgumentException("Id ends with a space.");
}
}
}
private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) {
Map<String, String> headers = new HashMap<>();
if (this.useMultipleWriteLocations) {
headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString());
}
if (consistencyLevel != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString());
}
if (options == null) {
if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
return headers;
}
Map<String, String> customOptions = options.getHeaders();
if (customOptions != null) {
headers.putAll(customOptions);
}
boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled;
if (options.isContentResponseOnWriteEnabled() != null) {
contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled();
}
if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
if (options.getIfMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag());
}
if(options.getIfNoneMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag());
}
if (options.getConsistencyLevel() != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString());
}
if (options.getIndexingDirective() != null) {
headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString());
}
if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) {
String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude);
}
if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) {
String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude);
}
if (!Strings.isNullOrEmpty(options.getSessionToken())) {
headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken());
}
if (options.getResourceTokenExpirySeconds() != null) {
headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY,
String.valueOf(options.getResourceTokenExpirySeconds()));
}
if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString());
} else if (options.getOfferType() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType());
}
if (options.getOfferThroughput() == null) {
if (options.getThroughputProperties() != null) {
Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties());
final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings();
OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null;
if (offerAutoscaleSettings != null) {
autoscaleAutoUpgradeProperties
= offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties();
}
if (offer.hasOfferThroughput() &&
(offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 ||
autoscaleAutoUpgradeProperties != null &&
autoscaleAutoUpgradeProperties
.getAutoscaleThroughputProperties()
.getIncrementPercent() >= 0)) {
throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with "
+ "fixed offer");
}
if (offer.hasOfferThroughput()) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput()));
} else if (offer.getOfferAutoScaleSettings() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS,
ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings()));
}
}
}
if (options.isQuotaInfoEnabled()) {
headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true));
}
if (options.isScriptLoggingEnabled()) {
headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true));
}
if (options.getDedicatedGatewayRequestOptions() != null &&
options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) {
headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS,
String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions())));
}
return headers;
}
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return this.resetSessionTokenRetryPolicy;
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Document document,
RequestOptions options) {
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs
.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object document,
RequestOptions options,
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) {
return collectionObs.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private void addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object objectDoc, RequestOptions options,
DocumentCollection collection) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
PartitionKeyInternal partitionKeyInternal = null;
if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else if (options != null && options.getPartitionKey() != null) {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey());
} else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) {
partitionKeyInternal = PartitionKeyInternal.getEmpty();
} else if (contentAsByteBuffer != null || objectDoc != null) {
InternalObjectNode internalObjectNode;
if (objectDoc instanceof InternalObjectNode) {
internalObjectNode = (InternalObjectNode) objectDoc;
} else if (objectDoc instanceof ObjectNode) {
internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc);
} else if (contentAsByteBuffer != null) {
contentAsByteBuffer.rewind();
internalObjectNode = new InternalObjectNode(contentAsByteBuffer);
} else {
throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null");
}
Instant serializationStartTime = Instant.now();
partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTime,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION
);
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
} else {
throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation.");
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
}
public static PartitionKeyInternal extractPartitionKeyValueFromDocument(
InternalObjectNode document,
PartitionKeyDefinition partitionKeyDefinition) {
if (partitionKeyDefinition != null) {
switch (partitionKeyDefinition.getKind()) {
case HASH:
String path = partitionKeyDefinition.getPaths().iterator().next();
List<String> parts = PathParser.getPathParts(path);
if (parts.size() >= 1) {
Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts);
if (value == null || value.getClass() == ObjectNode.class) {
value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
}
if (value instanceof PartitionKeyInternal) {
return (PartitionKeyInternal) value;
} else {
return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false);
}
}
break;
case MULTI_HASH:
Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()];
for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){
String partitionPath = partitionKeyDefinition.getPaths().get(pathIter);
List<String> partitionPathParts = PathParser.getPathParts(partitionPath);
partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts);
}
return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false);
default:
throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind());
}
}
return null;
}
private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
Object document,
RequestOptions options,
boolean disableAutomaticIdGeneration,
OperationType operationType) {
if (StringUtils.isEmpty(documentCollectionLink)) {
throw new IllegalArgumentException("documentCollectionLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Document, path, requestHeaders, options, content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return addPartitionKeyInformation(request, content, document, options, collectionObs);
}
private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink");
checkNotNull(serverBatchRequest, "expected non null serverBatchRequest");
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody()));
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Batch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> {
addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v);
return request;
});
}
private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request,
ServerBatchRequest serverBatchRequest,
DocumentCollection collection) {
if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) {
PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue();
PartitionKeyInternal partitionKeyInternal;
if (partitionKey.equals(PartitionKey.NONE)) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey);
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
} else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) {
request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId()));
} else {
throw new UnsupportedOperationException("Unknown Server request.");
}
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString());
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch()));
request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError()));
request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size());
return request;
}
private Mono<RxDocumentServiceRequest> populateHeaders(RxDocumentServiceRequest request, RequestVerb httpMethod) {
request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123());
if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null
|| this.cosmosAuthorizationTokenResolver != null || this.credential != null) {
String resourceName = request.getResourceAddress();
String authorization = this.getUserAuthorizationToken(
resourceName, request.getResourceType(), httpMethod, request.getHeaders(),
AuthorizationTokenType.PrimaryMasterKey, request.properties);
try {
authorization = URLEncoder.encode(authorization, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Failed to encode authtoken.", e);
}
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
}
if (this.apiType != null) {
request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString());
}
if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod))
&& !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
}
if (RequestVerb.PATCH.equals(httpMethod) &&
!request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH);
}
if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) {
request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
}
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
if (this.requiresFeedRangeFiltering(request)) {
return request.getFeedRange()
.populateFeedRangeFilteringHeaders(
this.getPartitionKeyRangeCache(),
request,
this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request))
.flatMap(this::populateAuthorizationHeader);
}
return this.populateAuthorizationHeader(request);
}
private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) {
if (request.getResourceType() != ResourceType.Document &&
request.getResourceType() != ResourceType.Conflict) {
return false;
}
switch (request.getOperationType()) {
case ReadFeed:
case Query:
case SqlQuery:
return request.getFeedRange() != null;
default:
return false;
}
}
@Override
public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) {
if (request == null) {
throw new IllegalArgumentException("request");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return request;
});
} else {
return Mono.just(request);
}
}
@Override
public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) {
if (httpHeaders == null) {
throw new IllegalArgumentException("httpHeaders");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return httpHeaders;
});
}
return Mono.just(httpHeaders);
}
@Override
public AuthorizationTokenType getAuthorizationTokenType() {
return this.authorizationTokenType;
}
@Override
public String getUserAuthorizationToken(String resourceName,
ResourceType resourceType,
RequestVerb requestVerb,
Map<String, String> headers,
AuthorizationTokenType tokenType,
Map<String, Object> properties) {
if (this.cosmosAuthorizationTokenResolver != null) {
return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(),
properties != null ? Collections.unmodifiableMap(properties) : null);
} else if (credential != null) {
return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName,
resourceType, headers);
} else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) {
return masterKeyOrResourceToken;
} else {
assert resourceTokensMap != null;
if(resourceType.equals(ResourceType.DatabaseAccount)) {
return this.firstResourceTokenFromPermissionFeed;
}
return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers);
}
}
private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) {
CosmosResourceType cosmosResourceType =
ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString());
if (cosmosResourceType == null) {
return CosmosResourceType.SYSTEM;
}
return cosmosResourceType;
}
void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) {
this.sessionContainer.setSessionToken(request, response.getResponseHeaders());
}
private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
Map<String, String> headers = requestPopulated.getHeaders();
assert (headers != null);
headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true");
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
);
});
}
private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.PUT)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PATCH);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(request).processMessage(request);
}
@Override
public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) {
try {
logger.debug("Creating a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Create);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance);
}
private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Upsert);
Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = Utils.getCollectionName(documentLink);
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Document typedDocument = documentFromObject(document, mapper);
return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = document.getSelfLink();
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (document == null) {
throw new IllegalArgumentException("document");
}
return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a database due to [{}]", e.getMessage());
return Mono.error(e);
}
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink,
Document document,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
if (document == null) {
throw new IllegalArgumentException("document");
}
logger.debug("Replacing a Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = serializeJsonToByteBuffer(document);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs);
return requestObs.flatMap(req -> replace(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> patchDocument(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink");
checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations");
logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options));
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Patch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(
request,
null,
null,
options,
collectionObs);
return requestObs.flatMap(req -> patch(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy);
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Deleting a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs);
return requestObs.flatMap(req -> this
.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> this
.deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting documents due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Reading a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> {
return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Document>> readDocuments(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return queryDocuments(collectionLink, "SELECT * FROM r", options);
}
@Override
public <T> Mono<FeedResponse<T>> readMany(
List<CosmosItemIdentity> itemIdentityList,
String collectionLink,
CosmosQueryRequestOptions options,
Class<T> klass) {
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink, null
);
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request);
return collectionObs
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache
.tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null);
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap =
new HashMap<>();
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
itemIdentityList
.forEach(itemIdentity -> {
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(
itemIdentity.getPartitionKey()),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
if (partitionRangeItemKeyMap.get(range) == null) {
List<CosmosItemIdentity> list = new ArrayList<>();
list.add(itemIdentity);
partitionRangeItemKeyMap.put(range, list);
} else {
List<CosmosItemIdentity> pairs =
partitionRangeItemKeyMap.get(range);
pairs.add(itemIdentity);
partitionRangeItemKeyMap.put(range, pairs);
}
});
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap;
rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap,
collection.getPartitionKey());
return createReadManyQuery(
resourceLink,
new SqlQuerySpec(DUMMY_SQL_QUERY),
options,
Document.class,
ResourceType.Document,
collection,
Collections.unmodifiableMap(rangeQueryMap))
.collectList()
.map(feedList -> {
List<T> finalList = new ArrayList<>();
HashMap<String, String> headers = new HashMap<>();
ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>();
double requestCharge = 0;
for (FeedResponse<Document> page : feedList) {
ConcurrentMap<String, QueryMetrics> pageQueryMetrics =
ModelBridgeInternal.queryMetrics(page);
if (pageQueryMetrics != null) {
pageQueryMetrics.forEach(
aggregatedQueryMetrics::putIfAbsent);
}
requestCharge += page.getRequestCharge();
finalList.addAll(page.getResults().stream().map(document ->
ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList()));
}
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double
.toString(requestCharge));
FeedResponse<T> frp = BridgeInternal
.createFeedResponse(finalList, headers);
return frp;
});
});
}
);
}
private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap(
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap,
PartitionKeyDefinition partitionKeyDefinition) {
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>();
String partitionKeySelector = createPkSelector(partitionKeyDefinition);
for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) {
SqlQuerySpec sqlQuerySpec;
if (partitionKeySelector.equals("[\"id\"]")) {
sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector);
} else {
sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector);
}
rangeQueryMap.put(entry.getKey(), sqlQuerySpec);
}
return rangeQueryMap;
}
private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(
List<CosmosItemIdentity> idPartitionKeyPairList,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( ");
for (int i = 0; i < idPartitionKeyPairList.size(); i++) {
CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i);
String idValue = itemIdentity.getId();
String idParamName = "@param" + i;
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
if (!Objects.equals(idValue, pkValue)) {
continue;
}
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append(idParamName);
if (i < idPartitionKeyPairList.size() - 1) {
queryStringBuilder.append(", ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE ( ");
for (int i = 0; i < itemIdentities.size(); i++) {
CosmosItemIdentity itemIdentity = itemIdentities.get(i);
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
String pkParamName = "@param" + (2 * i);
parameters.add(new SqlParameter(pkParamName, pkValue));
String idValue = itemIdentity.getId();
String idParamName = "@param" + (2 * i + 1);
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append("(");
queryStringBuilder.append("c.id = ");
queryStringBuilder.append(idParamName);
queryStringBuilder.append(" AND ");
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
queryStringBuilder.append(" )");
if (i < itemIdentities.size() - 1) {
queryStringBuilder.append(" OR ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) {
return partitionKeyDefinition.getPaths()
.stream()
.map(pathPart -> StringUtils.substring(pathPart, 1))
.map(pathPart -> StringUtils.replace(pathPart, "\"", "\\"))
.map(part -> "[\"" + part + "\"]")
.collect(Collectors.joining());
}
private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
DocumentCollection collection,
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) {
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(),
sqlQuery,
rangeQueryMap,
options,
collection.getResourceId(),
parentResourceLink,
activityId,
klass,
resourceTypeEnum);
return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync);
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, String query, CosmosQueryRequestOptions options) {
return queryDocuments(collectionLink, new SqlQuerySpec(query), options);
}
private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return new IDocumentQueryClient () {
@Override
public RxCollectionCache getCollectionCache() {
return RxDocumentClientImpl.this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return RxDocumentClientImpl.this.partitionKeyRangeCache;
}
@Override
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy;
}
@Override
public ConsistencyLevel getDefaultConsistencyLevelAsync() {
return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel();
}
@Override
public ConsistencyLevel getDesiredConsistencyLevelAsync() {
return RxDocumentClientImpl.this.consistencyLevel;
}
@Override
public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) {
if (operationContextAndListenerTuple == null) {
return RxDocumentClientImpl.this.query(request).single();
} else {
final OperationListener listener =
operationContextAndListenerTuple.getOperationListener();
final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext();
request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId());
listener.requestListener(operationContext, request);
return RxDocumentClientImpl.this.query(request).single().doOnNext(
response -> listener.responseListener(operationContext, response)
).doOnError(
ex -> listener.exceptionListener(operationContext, ex)
);
}
}
@Override
public QueryCompatibilityMode getQueryCompatibilityMode() {
return QueryCompatibilityMode.Default;
}
@Override
public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) {
return null;
}
};
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
SqlQuerySpecLogger.getInstance().logQuery(querySpec);
return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document);
}
@Override
public Flux<FeedResponse<Document>> queryDocumentChangeFeed(
final DocumentCollection collection,
final CosmosChangeFeedRequestOptions changeFeedOptions) {
checkNotNull(collection, "Argument 'collection' must not be null.");
ChangeFeedQueryImpl<Document> changeFeedQueryImpl = new ChangeFeedQueryImpl<>(
this,
ResourceType.Document,
Document.class,
collection.getAltLink(),
collection.getResourceId(),
changeFeedOptions);
return changeFeedQueryImpl.executeAsync();
}
@Override
public Flux<FeedResponse<Document>> readAllDocuments(
String collectionLink,
PartitionKey partitionKey,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (partitionKey == null) {
throw new IllegalArgumentException("partitionKey");
}
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null
);
Flux<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request).flux();
return collectionObs.flatMap(documentCollectionResourceResponse -> {
DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
String pkSelector = createPkSelector(pkDefinition);
SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector);
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
final CosmosQueryRequestOptions effectiveOptions =
ModelBridgeInternal.createQueryRequestOptions(options);
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> {
Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache
.tryLookupAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null).flux();
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(partitionKey),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
return createQueryInternal(
resourceLink,
querySpec,
ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()),
Document.class,
ResourceType.Document,
queryClient,
activityId);
});
},
invalidPartitionExceptionRetryPolicy);
});
}
@Override
public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() {
return queryPlanCache;
}
@Override
public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class,
Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT));
}
private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
validateResource(storedProcedure);
String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType,
ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
return request;
}
private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (udf == null) {
throw new IllegalArgumentException("udf");
}
validateResource(udf);
String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Create);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId());
RxDocumentClientImpl.validateResource(storedProcedure);
String path = Utils.joinPath(storedProcedure.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class,
Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
List<Object> procedureParams) {
return this.executeStoredProcedure(storedProcedureLink, null, procedureParams);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy);
}
@Override
public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy);
}
private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) {
try {
logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript);
requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ExecuteJavaScript,
ResourceType.StoredProcedure, path,
procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "",
requestHeaders, options);
if (retryPolicy != null) {
retryPolicy.onBeforeSendRequest(request);
}
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options))
.map(response -> {
this.captureSessionToken(request, response);
return toStoredProcedureResponse(response);
}));
} catch (Exception e) {
logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
DocumentClientRetryPolicy requestRetryPolicy,
boolean disableAutomaticIdGeneration) {
try {
logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size());
Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true));
} catch (Exception ex) {
logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex);
return Mono.error(ex);
}
}
@Override
public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path,
trigger, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId());
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(trigger.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Trigger, Trigger.class,
Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryTriggers(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger);
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (udf == null) {
throw new IllegalArgumentException("udf");
}
logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId());
validateResource(udf);
String path = Utils.joinPath(udf.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class,
Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
String query, CosmosQueryRequestOptions options) {
return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction);
}
@Override
public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Conflict, Conflict.class,
Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryConflicts(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict);
}
@Override
public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (user == null) {
throw new IllegalArgumentException("user");
}
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.User, path, user, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (user == null) {
throw new IllegalArgumentException("user");
}
logger.debug("Replacing a User. user id [{}]", user.getId());
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(user.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.User, path, user, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Deleting a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Reading a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.User, User.class,
Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) {
return queryUsers(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User);
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(clientEncryptionKeyLink)) {
throw new IllegalArgumentException("clientEncryptionKeyLink");
}
logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink);
String path = Utils.joinPath(clientEncryptionKeyLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink,
ClientEncryptionKey clientEncryptionKey, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId());
RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey,
String nameBasedLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey,
nameBasedLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId());
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(nameBasedLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey,
OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders,
options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class,
Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey);
}
@Override
public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy());
}
private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
if (permission == null) {
throw new IllegalArgumentException("permission");
}
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Permission, path, permission, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (permission == null) {
throw new IllegalArgumentException("permission");
}
logger.debug("Replacing a Permission. permission id [{}]", permission.getId());
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(permission.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Reading a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
return readFeed(options, ResourceType.Permission, Permission.class,
Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query,
CosmosQueryRequestOptions options) {
return queryPermissions(userLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission);
}
@Override
public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
if (offer == null) {
throw new IllegalArgumentException("offer");
}
logger.debug("Replacing an Offer. offer id [{}]", offer.getId());
RxDocumentClientImpl.validateResource(offer);
String path = Utils.joinPath(offer.getSelfLink(), null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace,
ResourceType.Offer, path, offer, null, null);
return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Offer>> readOffer(String offerLink) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(offerLink)) {
throw new IllegalArgumentException("offerLink");
}
logger.debug("Reading an Offer. offerLink [{}]", offerLink);
String path = Utils.joinPath(offerLink, null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Offer, Offer.class,
Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null));
}
private <T extends Resource> Flux<FeedResponse<T>> readFeed(CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options);
int maxPageSize = maxItemCount != null ? maxItemCount : -1;
final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options;
DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> {
Map<String, String> requestHeaders = new HashMap<>();
if (continuationToken != null) {
requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken);
}
requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize));
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions);
retryPolicy.onBeforeSendRequest(request);
return request;
};
Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper
.inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)),
retryPolicy);
return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, maxPageSize);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) {
return queryOffers(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer);
}
@Override
public Mono<DatabaseAccount> getDatabaseAccount() {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy),
documentClientRetryPolicy);
}
@Override
public DatabaseAccount getLatestDatabaseAccount() {
return this.globalEndpointManager.getLatestDatabaseAccount();
}
private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Getting Database Account");
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read,
ResourceType.DatabaseAccount, "",
(HashMap<String, String>) null,
null);
return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount);
} catch (Exception e) {
logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Object getSession() {
return this.sessionContainer;
}
public void setSession(Object sessionContainer) {
this.sessionContainer = (SessionContainer) sessionContainer;
}
@Override
public RxClientCollectionCache getCollectionCache() {
return this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return partitionKeyRangeCache;
}
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
return Flux.defer(() -> {
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null);
return this.populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
requestPopulated.setEndpointOverride(endpoint);
return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> {
String message = String.format("Failed to retrieve database account information. %s",
e.getCause() != null
? e.getCause().toString()
: e.toString());
logger.warn(message);
}).map(rsp -> rsp.getResource(DatabaseAccount.class))
.doOnNext(databaseAccount ->
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled()
&& BridgeInternal.isEnableMultipleWriteLocations(databaseAccount));
});
});
}
/**
* Certain requests must be routed through gateway even when the client connectivity mode is direct.
*
* @param request
* @return RxStoreModel
*/
private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) {
if (request.UseGatewayMode) {
return this.gatewayProxy;
}
ResourceType resourceType = request.getResourceType();
OperationType operationType = request.getOperationType();
if (resourceType == ResourceType.Offer ||
resourceType == ResourceType.ClientEncryptionKey ||
resourceType.isScript() && operationType != OperationType.ExecuteJavaScript ||
resourceType == ResourceType.PartitionKeyRange ||
resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) {
return this.gatewayProxy;
}
if (operationType == OperationType.Create
|| operationType == OperationType.Upsert) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection ||
resourceType == ResourceType.Permission) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Delete) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Replace) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Read) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else {
if ((operationType == OperationType.Query ||
operationType == OperationType.SqlQuery ||
operationType == OperationType.ReadFeed) &&
Utils.isCollectionChild(request.getResourceType())) {
if (request.getPartitionKeyRangeIdentity() == null &&
request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) {
return this.gatewayProxy;
}
}
return this.storeModel;
}
}
@Override
public void close() {
logger.info("Attempting to close client {}", this.clientId);
if (!closed.getAndSet(true)) {
this.activeClientsCnt.decrementAndGet();
logger.info("Shutting down ...");
logger.info("Closing Global Endpoint Manager ...");
LifeCycleUtils.closeQuietly(this.globalEndpointManager);
logger.info("Closing StoreClientFactory ...");
LifeCycleUtils.closeQuietly(this.storeClientFactory);
logger.info("Shutting down reactorHttpClient ...");
LifeCycleUtils.closeQuietly(this.reactorHttpClient);
logger.info("Shutting down CpuMonitor ...");
CpuMemoryMonitor.unregister(this);
if (this.throughputControlEnabled.get()) {
logger.info("Closing ThroughputControlStore ...");
this.throughputControlStore.close();
}
logger.info("Shutting down completed.");
} else {
logger.warn("Already shutdown!");
}
}
@Override
public ItemDeserializer getItemDeserializer() {
return this.itemDeserializer;
}
@Override
public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group can not be null");
if (this.throughputControlEnabled.compareAndSet(false, true)) {
this.throughputControlStore =
new ThroughputControlStore(
this.collectionCache,
this.connectionPolicy.getConnectionMode(),
this.partitionKeyRangeCache);
this.storeModel.enableThroughputControl(throughputControlStore);
}
this.throughputControlStore.enableThroughputControlGroup(group);
}
private static SqlQuerySpec createLogicalPartitionScanQuerySpec(
PartitionKey partitionKey,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE");
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey);
String pkParamName = "@pkValue";
parameters.add(new SqlParameter(pkParamName, pkValue));
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
@Override
public Mono<List<FeedRange>> getFeedRanges(String collectionLink) {
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
collectionLink,
new HashMap<>());
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null);
invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request);
return ObservableHelper.inlineIfPossibleAsObs(
() -> getFeedRangesInternal(request, collectionLink),
invalidPartitionExceptionRetryPolicy);
}
private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) {
logger.debug("getFeedRange collectionLink=[{}]", collectionLink);
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null,
request);
return collectionObs.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache
.tryGetOverlappingRangesAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null);
return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request));
});
}
private static List<FeedRange> toFeedRanges(
Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) {
final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v;
if (partitionKeyRangeList == null) {
request.forceNameCacheRefresh = true;
throw new InvalidPartitionException();
}
List<FeedRange> feedRanges = new ArrayList<>();
partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange)));
return feedRanges;
}
private static FeedRange toFeedRange(PartitionKeyRange pkRange) {
return new FeedRangeEpkImpl(pkRange.toRange());
}
} | class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener,
DiagnosticsClientContext {
private static final String tempMachineId = "uuid:" + UUID.randomUUID();
private static final AtomicInteger activeClientsCnt = new AtomicInteger(0);
private static final AtomicInteger clientIdGenerator = new AtomicInteger(0);
private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>(
PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey,
PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false);
private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " +
"ParallelDocumentQueryExecutioncontext, but not used";
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper();
private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer();
private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class);
private final String masterKeyOrResourceToken;
private final URI serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel consistencyLevel;
private final BaseAuthorizationTokenProvider authorizationTokenProvider;
private final UserAgentContainer userAgentContainer;
private final boolean hasAuthKeyResourceToken;
private final Configs configs;
private final boolean connectionSharingAcrossClientsEnabled;
private AzureKeyCredential credential;
private final TokenCredential tokenCredential;
private String[] tokenCredentialScopes;
private SimpleTokenCache tokenCredentialCache;
private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver;
AuthorizationTokenType authorizationTokenType;
private SessionContainer sessionContainer;
private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY;
private RxClientCollectionCache collectionCache;
private RxStoreModel gatewayProxy;
private RxStoreModel storeModel;
private GlobalAddressResolver addressResolver;
private RxPartitionKeyRangeCache partitionKeyRangeCache;
private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap;
private final boolean contentResponseOnWriteEnabled;
private Map<String, PartitionedQueryExecutionInfo> queryPlanCache;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final int clientId;
private ClientTelemetry clientTelemetry;
private ApiType apiType;
private IRetryPolicyFactory resetSessionTokenRetryPolicy;
/**
* Compatibility mode: Allows to specify compatibility mode used by client when
* making query requests. Should be removed when application/sql is no longer
* supported.
*/
private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default;
private final GlobalEndpointManager globalEndpointManager;
private final RetryPolicy retryPolicy;
private HttpClient reactorHttpClient;
private Function<HttpClient, HttpClient> httpClientInterceptor;
private volatile boolean useMultipleWriteLocations;
private StoreClientFactory storeClientFactory;
private GatewayServiceConfigurationReader gatewayConfigurationReader;
private final DiagnosticsClientConfig diagnosticsClientConfig;
private final AtomicBoolean throughputControlEnabled;
private ThroughputControlStore throughputControlStore;
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
public RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverride,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver;
}
private RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
List<Permission> permissionFeed,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs,
credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType);
if (permissionFeed != null && permissionFeed.size() > 0) {
this.resourceTokensMap = new HashMap<>();
for (Permission permission : permissionFeed) {
String[] segments = StringUtils.split(permission.getResourceLink(),
Constants.Properties.PATH_SEPARATOR.charAt(0));
if (segments.length <= 0) {
throw new IllegalArgumentException("resourceLink");
}
List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null;
PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false);
if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) {
throw new IllegalArgumentException(permission.getResourceLink());
}
partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName);
if (partitionKeyAndResourceTokenPairs == null) {
partitionKeyAndResourceTokenPairs = new ArrayList<>();
this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs);
}
PartitionKey partitionKey = permission.getResourcePartitionKey();
partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair(
partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty,
permission.getToken()));
logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]",
pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken());
}
if(this.resourceTokensMap.isEmpty()) {
throw new IllegalArgumentException("permissionFeed");
}
String firstToken = permissionFeed.get(0).getToken();
if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) {
this.firstResourceTokenFromPermissionFeed = firstToken;
}
}
}
RxDocumentClientImpl(URI serviceEndpoint,
String masterKeyOrResourceToken,
ConnectionPolicy connectionPolicy,
ConsistencyLevel consistencyLevel,
Configs configs,
AzureKeyCredential credential,
TokenCredential tokenCredential,
boolean sessionCapturingOverrideEnabled,
boolean connectionSharingAcrossClientsEnabled,
boolean contentResponseOnWriteEnabled,
CosmosClientMetadataCachesSnapshot metadataCachesSnapshot,
ApiType apiType) {
activeClientsCnt.incrementAndGet();
this.clientId = clientIdGenerator.incrementAndGet();
this.diagnosticsClientConfig = new DiagnosticsClientConfig();
this.diagnosticsClientConfig.withClientId(this.clientId);
this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt);
this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled);
this.diagnosticsClientConfig.withConsistency(consistencyLevel);
this.throughputControlEnabled = new AtomicBoolean(false);
logger.info(
"Initializing DocumentClient [{}] with"
+ " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]",
this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol());
try {
this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled;
this.configs = configs;
this.masterKeyOrResourceToken = masterKeyOrResourceToken;
this.serviceEndpoint = serviceEndpoint;
this.credential = credential;
this.tokenCredential = tokenCredential;
this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled;
this.authorizationTokenType = AuthorizationTokenType.Invalid;
if (this.credential != null) {
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.authorizationTokenProvider = null;
hasAuthKeyResourceToken = true;
this.authorizationTokenType = AuthorizationTokenType.ResourceToken;
} else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) {
this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken);
hasAuthKeyResourceToken = false;
this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey;
this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential);
} else {
hasAuthKeyResourceToken = false;
this.authorizationTokenProvider = null;
if (tokenCredential != null) {
this.tokenCredentialScopes = new String[] {
serviceEndpoint.getScheme() + ":
};
this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential
.getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes)));
this.authorizationTokenType = AuthorizationTokenType.AadToken;
}
}
if (connectionPolicy != null) {
this.connectionPolicy = connectionPolicy;
} else {
this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig());
}
this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode());
this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled());
this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled());
this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions());
this.diagnosticsClientConfig.withMachineId(tempMachineId);
boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled);
this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing);
this.consistencyLevel = consistencyLevel;
this.userAgentContainer = new UserAgentContainer();
String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix();
if (userAgentSuffix != null && userAgentSuffix.length() > 0) {
userAgentContainer.setSuffix(userAgentSuffix);
}
this.httpClientInterceptor = null;
this.reactorHttpClient = httpClient();
this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs);
this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy);
this.resetSessionTokenRetryPolicy = retryPolicy;
CpuMemoryMonitor.register(this);
this.queryPlanCache = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE));
this.apiType = apiType;
} catch (RuntimeException e) {
logger.error("unexpected failure in initializing client.", e);
close();
throw e;
}
}
@Override
public DiagnosticsClientConfig getConfig() {
return diagnosticsClientConfig;
}
@Override
public CosmosDiagnostics createDiagnostics() {
return BridgeInternal.createCosmosDiagnostics(this, this.globalEndpointManager);
}
private void initializeGatewayConfigurationReader() {
this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager);
DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount();
if (databaseAccount == null) {
logger.error("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
throw new RuntimeException("Client initialization failed."
+ " Check if the endpoint is reachable and if your auth token is valid. More info: https:
}
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount);
}
private void updateGatewayProxy() {
((RxGatewayStoreModel)this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader);
((RxGatewayStoreModel)this.gatewayProxy).setCollectionCache(this.collectionCache);
((RxGatewayStoreModel)this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache);
((RxGatewayStoreModel)this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations);
}
public void serialize(CosmosClientMetadataCachesSnapshot state) {
RxCollectionCache.serialize(state, this.collectionCache);
}
private void initializeDirectConnectivity() {
this.addressResolver = new GlobalAddressResolver(this,
this.reactorHttpClient,
this.globalEndpointManager,
this.configs.getProtocol(),
this,
this.collectionCache,
this.partitionKeyRangeCache,
userAgentContainer,
null,
this.connectionPolicy,
this.apiType);
this.storeClientFactory = new StoreClientFactory(
this.addressResolver,
this.diagnosticsClientConfig,
this.configs,
this.connectionPolicy,
this.userAgentContainer,
this.connectionSharingAcrossClientsEnabled,
this.clientTelemetry
);
this.createStoreModel(true);
}
DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() {
return new DatabaseAccountManagerInternal() {
@Override
public URI getServiceEndpoint() {
return RxDocumentClientImpl.this.getServiceEndpoint();
}
@Override
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
logger.info("Getting database account endpoint from {}", endpoint);
return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return RxDocumentClientImpl.this.getConnectionPolicy();
}
};
}
RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer,
ConsistencyLevel consistencyLevel,
QueryCompatibilityMode queryCompatibilityMode,
UserAgentContainer userAgentContainer,
GlobalEndpointManager globalEndpointManager,
HttpClient httpClient,
ApiType apiType) {
return new RxGatewayStoreModel(
this,
sessionContainer,
consistencyLevel,
queryCompatibilityMode,
userAgentContainer,
globalEndpointManager,
httpClient,
apiType);
}
private HttpClient httpClient() {
HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs)
.withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout())
.withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize())
.withProxy(this.connectionPolicy.getProxy())
.withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout());
if (connectionSharingAcrossClientsEnabled) {
return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig);
} else {
diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig);
return HttpClient.createFixed(httpClientConfig);
}
}
private void createStoreModel(boolean subscribeRntbdStatus) {
StoreClient storeClient = this.storeClientFactory.createStoreClient(this,
this.addressResolver,
this.sessionContainer,
this.gatewayConfigurationReader,
this,
this.useMultipleWriteLocations
);
this.storeModel = new ServerStoreModel(storeClient);
}
@Override
public URI getServiceEndpoint() {
return this.serviceEndpoint;
}
@Override
public URI getWriteEndpoint() {
return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null);
}
@Override
public URI getReadEndpoint() {
return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null);
}
@Override
public ConnectionPolicy getConnectionPolicy() {
return this.connectionPolicy;
}
@Override
public boolean isContentResponseOnWriteEnabled() {
return contentResponseOnWriteEnabled;
}
@Override
public ConsistencyLevel getConsistencyLevel() {
return consistencyLevel;
}
@Override
public ClientTelemetry getClientTelemetry() {
return this.clientTelemetry;
}
@Override
public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (database == null) {
throw new IllegalArgumentException("Database");
}
logger.debug("Creating a Database. id: [{}]", database.getId());
validateResource(database);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
logger.debug("Reading a Database. databaseLink: [{}]", databaseLink);
String path = Utils.joinPath(databaseLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Database, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class));
} catch (Exception e) {
logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT);
}
private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) {
switch (resourceTypeEnum) {
case Database:
return Paths.DATABASES_ROOT;
case DocumentCollection:
return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT);
case Document:
return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT);
case Offer:
return Paths.OFFERS_ROOT;
case User:
return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT);
case ClientEncryptionKey:
return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
case Permission:
return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT);
case Attachment:
return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT);
case StoredProcedure:
return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
case Trigger:
return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT);
case UserDefinedFunction:
return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
case Conflict:
return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT);
default:
throw new IllegalArgumentException("resource type not supported");
}
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) {
if (options == null) {
return null;
}
return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options);
}
private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) {
if (options == null) {
return null;
}
return options.getOperationContextAndListenerTuple();
}
private <T extends Resource> Flux<FeedResponse<T>> createQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum) {
String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum);
UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getCorrelationActivityId(options);
UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ?
correlationActivityIdOfRequestOptions : Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this,
getOperationContextAndListenerTuple(options));
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> createQueryInternal(
resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId),
invalidPartitionExceptionRetryPolicy);
}
private <T extends Resource> Flux<FeedResponse<T>> createQueryInternal(
String resourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
IDocumentQueryClient queryClient,
UUID activityId) {
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory
.createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery,
options, resourceLink, false, activityId,
Configs.isQueryPlanCachingEnabled(), queryPlanCache);
AtomicBoolean isFirstResponse = new AtomicBoolean(true);
return executionContext.flatMap(iDocumentQueryExecutionContext -> {
QueryInfo queryInfo = null;
if (iDocumentQueryExecutionContext instanceof PipelinedDocumentQueryExecutionContext) {
queryInfo = ((PipelinedDocumentQueryExecutionContext<T>) iDocumentQueryExecutionContext).getQueryInfo();
}
QueryInfo finalQueryInfo = queryInfo;
return iDocumentQueryExecutionContext.executeAsync()
.map(tFeedResponse -> {
if (finalQueryInfo != null) {
if (finalQueryInfo.hasSelectValue()) {
ModelBridgeInternal
.addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo);
}
if (isFirstResponse.compareAndSet(true, false)) {
ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse,
finalQueryInfo.getQueryPlanDiagnosticsContext());
}
}
return tFeedResponse;
});
});
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) {
return queryDatabases(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database);
}
@Override
public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink,
DocumentCollection collection, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink,
DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink,
collection.getId());
validateResource(collection);
String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
});
} catch (Exception e) {
logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (collection == null) {
throw new IllegalArgumentException("collection");
}
logger.debug("Replacing a Collection. id: [{}]", collection.getId());
validateResource(collection);
String path = Utils.joinPath(collection.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class))
.doOnNext(resourceResponse -> {
if (resourceResponse.getResource() != null) {
this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(),
getAltLink(resourceResponse.getResource()),
resourceResponse.getResponseHeaders());
}
});
} catch (Exception e) {
logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.DELETE)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated));
}
private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated ->
this.getStoreProxy(requestPopulated).processMessage(requestPopulated)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
));
}
@Override
public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class));
} catch (Exception e) {
logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class,
Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection);
}
@Override
public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection);
}
private static String serializeProcedureParams(List<Object> objectArray) {
String[] stringArray = new String[objectArray.size()];
for (int i = 0; i < objectArray.size(); ++i) {
Object object = objectArray.get(i);
if (object instanceof JsonSerializable) {
stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object);
} else {
try {
stringArray[i] = mapper.writeValueAsString(object);
} catch (IOException e) {
throw new IllegalArgumentException("Can't serialize the object into the json string", e);
}
}
}
return String.format("[%s]", StringUtils.join(stringArray, ","));
}
private static void validateResource(Resource resource) {
if (!StringUtils.isEmpty(resource.getId())) {
if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 ||
resource.getId().indexOf('?') != -1 || resource.getId().indexOf('
throw new IllegalArgumentException("Id contains illegal chars.");
}
if (resource.getId().endsWith(" ")) {
throw new IllegalArgumentException("Id ends with a space.");
}
}
}
private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) {
Map<String, String> headers = new HashMap<>();
if (this.useMultipleWriteLocations) {
headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString());
}
if (consistencyLevel != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString());
}
if (options == null) {
if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
return headers;
}
Map<String, String> customOptions = options.getHeaders();
if (customOptions != null) {
headers.putAll(customOptions);
}
boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled;
if (options.isContentResponseOnWriteEnabled() != null) {
contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled();
}
if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) {
headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL);
}
if (options.getIfMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag());
}
if(options.getIfNoneMatchETag() != null) {
headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag());
}
if (options.getConsistencyLevel() != null) {
headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString());
}
if (options.getIndexingDirective() != null) {
headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString());
}
if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) {
String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude);
}
if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) {
String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ",");
headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude);
}
if (!Strings.isNullOrEmpty(options.getSessionToken())) {
headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken());
}
if (options.getResourceTokenExpirySeconds() != null) {
headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY,
String.valueOf(options.getResourceTokenExpirySeconds()));
}
if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString());
} else if (options.getOfferType() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType());
}
if (options.getOfferThroughput() == null) {
if (options.getThroughputProperties() != null) {
Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties());
final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings();
OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null;
if (offerAutoscaleSettings != null) {
autoscaleAutoUpgradeProperties
= offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties();
}
if (offer.hasOfferThroughput() &&
(offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 ||
autoscaleAutoUpgradeProperties != null &&
autoscaleAutoUpgradeProperties
.getAutoscaleThroughputProperties()
.getIncrementPercent() >= 0)) {
throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with "
+ "fixed offer");
}
if (offer.hasOfferThroughput()) {
headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput()));
} else if (offer.getOfferAutoScaleSettings() != null) {
headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS,
ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings()));
}
}
}
if (options.isQuotaInfoEnabled()) {
headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true));
}
if (options.isScriptLoggingEnabled()) {
headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true));
}
if (options.getDedicatedGatewayRequestOptions() != null &&
options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) {
headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS,
String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions())));
}
return headers;
}
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return this.resetSessionTokenRetryPolicy;
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Document document,
RequestOptions options) {
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs
.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object document,
RequestOptions options,
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) {
return collectionObs.map(collectionValueHolder -> {
addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v);
return request;
});
}
private void addPartitionKeyInformation(RxDocumentServiceRequest request,
ByteBuffer contentAsByteBuffer,
Object objectDoc, RequestOptions options,
DocumentCollection collection) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
PartitionKeyInternal partitionKeyInternal = null;
if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else if (options != null && options.getPartitionKey() != null) {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey());
} else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) {
partitionKeyInternal = PartitionKeyInternal.getEmpty();
} else if (contentAsByteBuffer != null || objectDoc != null) {
InternalObjectNode internalObjectNode;
if (objectDoc instanceof InternalObjectNode) {
internalObjectNode = (InternalObjectNode) objectDoc;
} else if (objectDoc instanceof ObjectNode) {
internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc);
} else if (contentAsByteBuffer != null) {
contentAsByteBuffer.rewind();
internalObjectNode = new InternalObjectNode(contentAsByteBuffer);
} else {
throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null");
}
Instant serializationStartTime = Instant.now();
partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTime,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION
);
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
} else {
throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation.");
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
}
public static PartitionKeyInternal extractPartitionKeyValueFromDocument(
InternalObjectNode document,
PartitionKeyDefinition partitionKeyDefinition) {
if (partitionKeyDefinition != null) {
switch (partitionKeyDefinition.getKind()) {
case HASH:
String path = partitionKeyDefinition.getPaths().iterator().next();
List<String> parts = PathParser.getPathParts(path);
if (parts.size() >= 1) {
Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts);
if (value == null || value.getClass() == ObjectNode.class) {
value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
}
if (value instanceof PartitionKeyInternal) {
return (PartitionKeyInternal) value;
} else {
return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false);
}
}
break;
case MULTI_HASH:
Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()];
for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){
String partitionPath = partitionKeyDefinition.getPaths().get(pathIter);
List<String> partitionPathParts = PathParser.getPathParts(partitionPath);
partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts);
}
return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false);
default:
throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind());
}
}
return null;
}
private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
Object document,
RequestOptions options,
boolean disableAutomaticIdGeneration,
OperationType operationType) {
if (StringUtils.isEmpty(documentCollectionLink)) {
throw new IllegalArgumentException("documentCollectionLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper);
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Document, path, requestHeaders, options, content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return addPartitionKeyInformation(request, content, document, options, collectionObs);
}
private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy,
String documentCollectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink");
checkNotNull(serverBatchRequest, "expected non null serverBatchRequest");
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody()));
Instant serializationEndTimeUTC = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTimeUTC,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Batch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (requestRetryPolicy != null) {
requestRetryPolicy.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> {
addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v);
return request;
});
}
private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request,
ServerBatchRequest serverBatchRequest,
DocumentCollection collection) {
if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) {
PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue();
PartitionKeyInternal partitionKeyInternal;
if (partitionKey.equals(PartitionKey.NONE)) {
PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey();
partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition);
} else {
partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey);
}
request.setPartitionKeyInternal(partitionKeyInternal);
request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson()));
} else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) {
request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId()));
} else {
throw new UnsupportedOperationException("Unknown Server request.");
}
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString());
request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch()));
request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError()));
request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size());
return request;
}
private Mono<RxDocumentServiceRequest> populateHeaders(RxDocumentServiceRequest request, RequestVerb httpMethod) {
request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123());
if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null
|| this.cosmosAuthorizationTokenResolver != null || this.credential != null) {
String resourceName = request.getResourceAddress();
String authorization = this.getUserAuthorizationToken(
resourceName, request.getResourceType(), httpMethod, request.getHeaders(),
AuthorizationTokenType.PrimaryMasterKey, request.properties);
try {
authorization = URLEncoder.encode(authorization, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Failed to encode authtoken.", e);
}
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
}
if (this.apiType != null) {
request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString());
}
if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod))
&& !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
}
if (RequestVerb.PATCH.equals(httpMethod) &&
!request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) {
request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH);
}
if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) {
request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
}
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
if (this.requiresFeedRangeFiltering(request)) {
return request.getFeedRange()
.populateFeedRangeFilteringHeaders(
this.getPartitionKeyRangeCache(),
request,
this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request))
.flatMap(this::populateAuthorizationHeader);
}
return this.populateAuthorizationHeader(request);
}
private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) {
if (request.getResourceType() != ResourceType.Document &&
request.getResourceType() != ResourceType.Conflict) {
return false;
}
switch (request.getOperationType()) {
case ReadFeed:
case Query:
case SqlQuery:
return request.getFeedRange() != null;
default:
return false;
}
}
@Override
public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) {
if (request == null) {
throw new IllegalArgumentException("request");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return request;
});
} else {
return Mono.just(request);
}
}
@Override
public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) {
if (httpHeaders == null) {
throw new IllegalArgumentException("httpHeaders");
}
if (this.authorizationTokenType == AuthorizationTokenType.AadToken) {
return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache)
.map(authorization -> {
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
return httpHeaders;
});
}
return Mono.just(httpHeaders);
}
@Override
public AuthorizationTokenType getAuthorizationTokenType() {
return this.authorizationTokenType;
}
@Override
public String getUserAuthorizationToken(String resourceName,
ResourceType resourceType,
RequestVerb requestVerb,
Map<String, String> headers,
AuthorizationTokenType tokenType,
Map<String, Object> properties) {
if (this.cosmosAuthorizationTokenResolver != null) {
return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(),
properties != null ? Collections.unmodifiableMap(properties) : null);
} else if (credential != null) {
return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName,
resourceType, headers);
} else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) {
return masterKeyOrResourceToken;
} else {
assert resourceTokensMap != null;
if(resourceType.equals(ResourceType.DatabaseAccount)) {
return this.firstResourceTokenFromPermissionFeed;
}
return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers);
}
}
private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) {
CosmosResourceType cosmosResourceType =
ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString());
if (cosmosResourceType == null) {
return CosmosResourceType.SYSTEM;
}
return cosmosResourceType;
}
void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) {
this.sessionContainer.setSessionToken(request, response.getResponseHeaders());
}
private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
RxStoreModel storeProxy = this.getStoreProxy(requestPopulated);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple);
});
}
private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request,
DocumentClientRetryPolicy documentClientRetryPolicy,
OperationContextAndListenerTuple operationContextAndListenerTuple) {
return populateHeaders(request, RequestVerb.POST)
.flatMap(requestPopulated -> {
Map<String, String> headers = requestPopulated.getHeaders();
assert (headers != null);
headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true");
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple)
.map(response -> {
this.captureSessionToken(requestPopulated, response);
return response;
}
);
});
}
private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
return populateHeaders(request, RequestVerb.PUT)
.flatMap(requestPopulated -> {
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(requestPopulated).processMessage(requestPopulated);
});
}
private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PATCH);
if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) {
documentClientRetryPolicy.getRetryContext().updateEndTime();
}
return getStoreProxy(request).processMessage(request);
}
@Override
public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) {
try {
logger.debug("Creating a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Create);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance);
}
private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document,
RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink);
Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document,
options, disableAutomaticIdGeneration, OperationType.Upsert);
Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
} catch (Exception e) {
logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = Utils.getCollectionName(documentLink);
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
if (document == null) {
throw new IllegalArgumentException("document");
}
Document typedDocument = documentFromObject(document, mapper);
return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
if (options == null || options.getPartitionKey() == null) {
String collectionLink = document.getSelfLink();
requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options);
}
DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy;
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (document == null) {
throw new IllegalArgumentException("document");
}
return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance);
} catch (Exception e) {
logger.debug("Failure in replacing a database due to [{}]", e.getMessage());
return Mono.error(e);
}
}
private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink,
Document document,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
if (document == null) {
throw new IllegalArgumentException("document");
}
logger.debug("Replacing a Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = serializeJsonToByteBuffer(document);
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs);
return requestObs.flatMap(req -> replace(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> patchDocument(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink,
CosmosPatchOperations cosmosPatchOperations,
RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink");
checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations");
logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink);
final String path = Utils.joinPath(documentLink, null);
final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch);
Instant serializationStartTimeUTC = Instant.now();
ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options));
Instant serializationEndTime = Instant.now();
SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics(
serializationStartTimeUTC,
serializationEndTime,
SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Patch,
ResourceType.Document,
path,
requestHeaders,
options,
content);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics);
if (serializationDiagnosticsContext != null) {
serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(
request,
null,
null,
options,
collectionObs);
return requestObs.flatMap(req -> patch(request, retryPolicyInstance)
.map(resp -> toResourceResponse(resp, Document.class)));
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy);
}
@Override
public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Deleting a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs);
return requestObs.flatMap(req -> this
.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy),
requestRetryPolicy);
}
private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink);
String path = Utils.joinPath(collectionLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> this
.deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))
.map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)));
} catch (Exception e) {
logger.debug("Failure in deleting documents due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(documentLink)) {
throw new IllegalArgumentException("documentLink");
}
logger.debug("Reading a Document. documentLink: [{}]", documentLink);
String path = Utils.joinPath(documentLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Document, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request);
Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs);
return requestObs.flatMap(req -> {
return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a document due to [{}]", e.getMessage());
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Document>> readDocuments(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return queryDocuments(collectionLink, "SELECT * FROM r", options);
}
@Override
public <T> Mono<FeedResponse<T>> readMany(
List<CosmosItemIdentity> itemIdentityList,
String collectionLink,
CosmosQueryRequestOptions options,
Class<T> klass) {
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink, null
);
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request);
return collectionObs
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache
.tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null);
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap =
new HashMap<>();
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
itemIdentityList
.forEach(itemIdentity -> {
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(
itemIdentity.getPartitionKey()),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
if (partitionRangeItemKeyMap.get(range) == null) {
List<CosmosItemIdentity> list = new ArrayList<>();
list.add(itemIdentity);
partitionRangeItemKeyMap.put(range, list);
} else {
List<CosmosItemIdentity> pairs =
partitionRangeItemKeyMap.get(range);
pairs.add(itemIdentity);
partitionRangeItemKeyMap.put(range, pairs);
}
});
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap;
rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap,
collection.getPartitionKey());
return createReadManyQuery(
resourceLink,
new SqlQuerySpec(DUMMY_SQL_QUERY),
options,
Document.class,
ResourceType.Document,
collection,
Collections.unmodifiableMap(rangeQueryMap))
.collectList()
.map(feedList -> {
List<T> finalList = new ArrayList<>();
HashMap<String, String> headers = new HashMap<>();
ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>();
double requestCharge = 0;
for (FeedResponse<Document> page : feedList) {
ConcurrentMap<String, QueryMetrics> pageQueryMetrics =
ModelBridgeInternal.queryMetrics(page);
if (pageQueryMetrics != null) {
pageQueryMetrics.forEach(
aggregatedQueryMetrics::putIfAbsent);
}
requestCharge += page.getRequestCharge();
finalList.addAll(page.getResults().stream().map(document ->
ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList()));
}
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double
.toString(requestCharge));
FeedResponse<T> frp = BridgeInternal
.createFeedResponse(finalList, headers);
return frp;
});
});
}
);
}
private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap(
Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap,
PartitionKeyDefinition partitionKeyDefinition) {
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>();
String partitionKeySelector = createPkSelector(partitionKeyDefinition);
for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) {
SqlQuerySpec sqlQuerySpec;
if (partitionKeySelector.equals("[\"id\"]")) {
sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector);
} else {
sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelector);
}
rangeQueryMap.put(entry.getKey(), sqlQuerySpec);
}
return rangeQueryMap;
}
private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(
List<CosmosItemIdentity> idPartitionKeyPairList,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( ");
for (int i = 0; i < idPartitionKeyPairList.size(); i++) {
CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i);
String idValue = itemIdentity.getId();
String idParamName = "@param" + i;
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
if (!Objects.equals(idValue, pkValue)) {
continue;
}
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append(idParamName);
if (i < idPartitionKeyPairList.size() - 1) {
queryStringBuilder.append(", ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE ( ");
for (int i = 0; i < itemIdentities.size(); i++) {
CosmosItemIdentity itemIdentity = itemIdentities.get(i);
PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey();
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey);
String pkParamName = "@param" + (2 * i);
parameters.add(new SqlParameter(pkParamName, pkValue));
String idValue = itemIdentity.getId();
String idParamName = "@param" + (2 * i + 1);
parameters.add(new SqlParameter(idParamName, idValue));
queryStringBuilder.append("(");
queryStringBuilder.append("c.id = ");
queryStringBuilder.append(idParamName);
queryStringBuilder.append(" AND ");
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
queryStringBuilder.append(" )");
if (i < itemIdentities.size() - 1) {
queryStringBuilder.append(" OR ");
}
}
queryStringBuilder.append(" )");
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) {
return partitionKeyDefinition.getPaths()
.stream()
.map(pathPart -> StringUtils.substring(pathPart, 1))
.map(pathPart -> StringUtils.replace(pathPart, "\"", "\\"))
.map(part -> "[\"" + part + "\"]")
.collect(Collectors.joining());
}
private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery(
String parentResourceLink,
SqlQuerySpec sqlQuery,
CosmosQueryRequestOptions options,
Class<T> klass,
ResourceType resourceTypeEnum,
DocumentCollection collection,
Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) {
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
Flux<? extends IDocumentQueryExecutionContext<T>> executionContext =
DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(),
sqlQuery,
rangeQueryMap,
options,
collection.getResourceId(),
parentResourceLink,
activityId,
klass,
resourceTypeEnum);
return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync);
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, String query, CosmosQueryRequestOptions options) {
return queryDocuments(collectionLink, new SqlQuerySpec(query), options);
}
private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) {
return new IDocumentQueryClient () {
@Override
public RxCollectionCache getCollectionCache() {
return RxDocumentClientImpl.this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return RxDocumentClientImpl.this.partitionKeyRangeCache;
}
@Override
public IRetryPolicyFactory getResetSessionTokenRetryPolicy() {
return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy;
}
@Override
public ConsistencyLevel getDefaultConsistencyLevelAsync() {
return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel();
}
@Override
public ConsistencyLevel getDesiredConsistencyLevelAsync() {
return RxDocumentClientImpl.this.consistencyLevel;
}
@Override
public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) {
if (operationContextAndListenerTuple == null) {
return RxDocumentClientImpl.this.query(request).single();
} else {
final OperationListener listener =
operationContextAndListenerTuple.getOperationListener();
final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext();
request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId());
listener.requestListener(operationContext, request);
return RxDocumentClientImpl.this.query(request).single().doOnNext(
response -> listener.responseListener(operationContext, response)
).doOnError(
ex -> listener.exceptionListener(operationContext, ex)
);
}
}
@Override
public QueryCompatibilityMode getQueryCompatibilityMode() {
return QueryCompatibilityMode.Default;
}
@Override
public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) {
return null;
}
};
}
@Override
public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
SqlQuerySpecLogger.getInstance().logQuery(querySpec);
return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document);
}
@Override
public Flux<FeedResponse<Document>> queryDocumentChangeFeed(
final DocumentCollection collection,
final CosmosChangeFeedRequestOptions changeFeedOptions) {
checkNotNull(collection, "Argument 'collection' must not be null.");
ChangeFeedQueryImpl<Document> changeFeedQueryImpl = new ChangeFeedQueryImpl<>(
this,
ResourceType.Document,
Document.class,
collection.getAltLink(),
collection.getResourceId(),
changeFeedOptions);
return changeFeedQueryImpl.executeAsync();
}
@Override
public Flux<FeedResponse<Document>> readAllDocuments(
String collectionLink,
PartitionKey partitionKey,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (partitionKey == null) {
throw new IllegalArgumentException("partitionKey");
}
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null
);
Flux<Utils.ValueHolder<DocumentCollection>> collectionObs =
collectionCache.resolveCollectionAsync(null, request).flux();
return collectionObs.flatMap(documentCollectionResourceResponse -> {
DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
PartitionKeyDefinition pkDefinition = collection.getPartitionKey();
String pkSelector = createPkSelector(pkDefinition);
SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector);
String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document);
UUID activityId = Utils.randomUUID();
IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options));
final CosmosQueryRequestOptions effectiveOptions =
ModelBridgeInternal.createQueryRequestOptions(options);
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
resourceLink,
ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions));
return ObservableHelper.fluxInlineIfPossibleAsObs(
() -> {
Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache
.tryLookupAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(),
null,
null).flux();
return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> {
CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v;
if (routingMap == null) {
throw new IllegalStateException("Failed to get routing map.");
}
String effectivePartitionKeyString = PartitionKeyInternalHelper
.getEffectivePartitionKeyString(
BridgeInternal.getPartitionKeyInternal(partitionKey),
pkDefinition);
PartitionKeyRange range =
routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString);
return createQueryInternal(
resourceLink,
querySpec,
ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()),
Document.class,
ResourceType.Document,
queryClient,
activityId);
});
},
invalidPartitionExceptionRetryPolicy);
});
}
@Override
public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() {
return queryPlanCache;
}
@Override
public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class,
Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT));
}
private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
validateResource(storedProcedure);
String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType,
ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
return request;
}
private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (udf == null) {
throw new IllegalArgumentException("udf");
}
validateResource(udf);
String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Create);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink,
StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]",
collectionLink, storedProcedure.getId());
RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (storedProcedure == null) {
throw new IllegalArgumentException("storedProcedure");
}
logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId());
RxDocumentClientImpl.validateResource(storedProcedure);
String path = Utils.joinPath(storedProcedure.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy);
}
private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(storedProcedureLink)) {
throw new IllegalArgumentException("storedProcedureLink");
}
logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class));
} catch (Exception e) {
logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class,
Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
List<Object> procedureParams) {
return this.executeStoredProcedure(storedProcedureLink, null, procedureParams);
}
@Override
public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy);
}
@Override
public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
boolean disableAutomaticIdGeneration) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy);
}
private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink,
RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) {
try {
logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink);
String path = Utils.joinPath(storedProcedureLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript);
requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ExecuteJavaScript,
ResourceType.StoredProcedure, path,
procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "",
requestHeaders, options);
if (retryPolicy != null) {
retryPolicy.onBeforeSendRequest(request);
}
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options))
.map(response -> {
this.captureSessionToken(request, response);
return toStoredProcedureResponse(response);
}));
} catch (Exception e) {
logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink,
ServerBatchRequest serverBatchRequest,
RequestOptions options,
DocumentClientRetryPolicy requestRetryPolicy,
boolean disableAutomaticIdGeneration) {
try {
logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size());
Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration);
Mono<RxDocumentServiceResponse> responseObservable =
requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)));
return responseObservable
.map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true));
} catch (Exception ex) {
logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex);
return Mono.error(ex);
}
}
@Override
public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink,
trigger.getId());
RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path,
trigger, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (trigger == null) {
throw new IllegalArgumentException("trigger");
}
logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId());
RxDocumentClientImpl.validateResource(trigger);
String path = Utils.joinPath(trigger.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(triggerLink)) {
throw new IllegalArgumentException("triggerLink");
}
logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink);
String path = Utils.joinPath(triggerLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Trigger, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class));
} catch (Exception e) {
logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Trigger, Trigger.class,
Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryTriggers(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger);
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Create);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink,
UserDefinedFunction udf, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink,
UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink,
udf.getId());
RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options,
OperationType.Upsert);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (udf == null) {
throw new IllegalArgumentException("udf");
}
logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId());
validateResource(udf);
String path = Utils.joinPath(udf.getSelfLink(), null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null){
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(udfLink)) {
throw new IllegalArgumentException("udfLink");
}
logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink);
String path = Utils.joinPath(udfLink, null);
Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class));
} catch (Exception e) {
logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink,
CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class,
Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
String query, CosmosQueryRequestOptions options) {
return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink,
SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction);
}
@Override
public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
return readFeed(options, ResourceType.Conflict, Conflict.class,
Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query,
CosmosQueryRequestOptions options) {
return queryConflicts(collectionLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict);
}
@Override
public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(conflictLink)) {
throw new IllegalArgumentException("conflictLink");
}
logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink);
String path = Utils.joinPath(conflictLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options);
Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options);
return reqObs.flatMap(req -> {
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class));
});
} catch (Exception e) {
logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId());
RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (user == null) {
throw new IllegalArgumentException("user");
}
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.User, path, user, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (user == null) {
throw new IllegalArgumentException("user");
}
logger.debug("Replacing a User. user id [{}]", user.getId());
RxDocumentClientImpl.validateResource(user);
String path = Utils.joinPath(user.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.User, path, user, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Deleting a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
logger.debug("Reading a User. userLink [{}]", userLink);
String path = Utils.joinPath(userLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.User, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class));
} catch (Exception e) {
logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.User, User.class,
Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) {
return queryUsers(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User);
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(clientEncryptionKeyLink)) {
throw new IllegalArgumentException("clientEncryptionKeyLink");
}
logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink);
String path = Utils.joinPath(clientEncryptionKeyLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink,
ClientEncryptionKey clientEncryptionKey, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId());
RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options,
OperationType operationType) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey,
String nameBasedLink,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey,
nameBasedLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (clientEncryptionKey == null) {
throw new IllegalArgumentException("clientEncryptionKey");
}
logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId());
RxDocumentClientImpl.validateResource(clientEncryptionKey);
String path = Utils.joinPath(nameBasedLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey,
OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders,
options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class));
} catch (Exception e) {
logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(databaseLink)) {
throw new IllegalArgumentException("databaseLink");
}
return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class,
Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, String query,
CosmosQueryRequestOptions options) {
return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey);
}
@Override
public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy());
}
private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Create);
return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission,
RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission,
RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId());
RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options,
OperationType.Upsert);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission,
RequestOptions options, OperationType operationType) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
if (permission == null) {
throw new IllegalArgumentException("permission");
}
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
operationType, ResourceType.Permission, path, permission, requestHeaders, options);
return request;
}
@Override
public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (permission == null) {
throw new IllegalArgumentException("permission");
}
logger.debug("Replacing a Permission. permission id [{}]", permission.getId());
RxDocumentClientImpl.validateResource(permission);
String path = Utils.joinPath(permission.getSelfLink(), null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options,
DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Delete, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) {
try {
if (StringUtils.isEmpty(permissionLink)) {
throw new IllegalArgumentException("permissionLink");
}
logger.debug("Reading a Permission. permissionLink [{}]", permissionLink);
String path = Utils.joinPath(permissionLink, null);
Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Permission, path, requestHeaders, options);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class));
} catch (Exception e) {
logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) {
if (StringUtils.isEmpty(userLink)) {
throw new IllegalArgumentException("userLink");
}
return readFeed(options, ResourceType.Permission, Permission.class,
Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT));
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query,
CosmosQueryRequestOptions options) {
return queryPermissions(userLink, new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec,
CosmosQueryRequestOptions options) {
return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission);
}
@Override
public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy);
}
private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
if (offer == null) {
throw new IllegalArgumentException("offer");
}
logger.debug("Replacing an Offer. offer id [{}]", offer.getId());
RxDocumentClientImpl.validateResource(offer);
String path = Utils.joinPath(offer.getSelfLink(), null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace,
ResourceType.Offer, path, offer, null, null);
return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Mono<ResourceResponse<Offer>> readOffer(String offerLink) {
DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance);
}
private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) {
try {
if (StringUtils.isEmpty(offerLink)) {
throw new IllegalArgumentException("offerLink");
}
logger.debug("Reading an Offer. offerLink [{}]", offerLink);
String path = Utils.joinPath(offerLink, null);
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null);
if (retryPolicyInstance != null) {
retryPolicyInstance.onBeforeSendRequest(request);
}
return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class));
} catch (Exception e) {
logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
@Override
public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) {
return readFeed(options, ResourceType.Offer, Offer.class,
Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null));
}
private <T extends Resource> Flux<FeedResponse<T>> readFeed(CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options);
int maxPageSize = maxItemCount != null ? maxItemCount : -1;
final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options;
DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> {
Map<String, String> requestHeaders = new HashMap<>();
if (continuationToken != null) {
requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken);
}
requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize));
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions);
retryPolicy.onBeforeSendRequest(request);
return request;
};
Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper
.inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)),
retryPolicy);
return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, maxPageSize);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) {
return queryOffers(new SqlQuerySpec(query), options);
}
@Override
public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer);
}
@Override
public Mono<DatabaseAccount> getDatabaseAccount() {
DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy();
return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy),
documentClientRetryPolicy);
}
@Override
public DatabaseAccount getLatestDatabaseAccount() {
return this.globalEndpointManager.getLatestDatabaseAccount();
}
private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) {
try {
logger.debug("Getting Database Account");
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read,
ResourceType.DatabaseAccount, "",
(HashMap<String, String>) null,
null);
return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount);
} catch (Exception e) {
logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e);
return Mono.error(e);
}
}
public Object getSession() {
return this.sessionContainer;
}
public void setSession(Object sessionContainer) {
this.sessionContainer = (SessionContainer) sessionContainer;
}
@Override
public RxClientCollectionCache getCollectionCache() {
return this.collectionCache;
}
@Override
public RxPartitionKeyRangeCache getPartitionKeyRangeCache() {
return partitionKeyRangeCache;
}
public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) {
return Flux.defer(() -> {
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this,
OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null);
return this.populateHeaders(request, RequestVerb.GET)
.flatMap(requestPopulated -> {
requestPopulated.setEndpointOverride(endpoint);
return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> {
String message = String.format("Failed to retrieve database account information. %s",
e.getCause() != null
? e.getCause().toString()
: e.toString());
logger.warn(message);
}).map(rsp -> rsp.getResource(DatabaseAccount.class))
.doOnNext(databaseAccount ->
this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled()
&& BridgeInternal.isEnableMultipleWriteLocations(databaseAccount));
});
});
}
/**
* Certain requests must be routed through gateway even when the client connectivity mode is direct.
*
* @param request
* @return RxStoreModel
*/
private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) {
if (request.UseGatewayMode) {
return this.gatewayProxy;
}
ResourceType resourceType = request.getResourceType();
OperationType operationType = request.getOperationType();
if (resourceType == ResourceType.Offer ||
resourceType == ResourceType.ClientEncryptionKey ||
resourceType.isScript() && operationType != OperationType.ExecuteJavaScript ||
resourceType == ResourceType.PartitionKeyRange ||
resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) {
return this.gatewayProxy;
}
if (operationType == OperationType.Create
|| operationType == OperationType.Upsert) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection ||
resourceType == ResourceType.Permission) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Delete) {
if (resourceType == ResourceType.Database ||
resourceType == ResourceType.User ||
resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Replace) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else if (operationType == OperationType.Read) {
if (resourceType == ResourceType.DocumentCollection) {
return this.gatewayProxy;
} else {
return this.storeModel;
}
} else {
if ((operationType == OperationType.Query ||
operationType == OperationType.SqlQuery ||
operationType == OperationType.ReadFeed) &&
Utils.isCollectionChild(request.getResourceType())) {
if (request.getPartitionKeyRangeIdentity() == null &&
request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) {
return this.gatewayProxy;
}
}
return this.storeModel;
}
}
@Override
public void close() {
logger.info("Attempting to close client {}", this.clientId);
if (!closed.getAndSet(true)) {
activeClientsCnt.decrementAndGet();
logger.info("Shutting down ...");
logger.info("Closing Global Endpoint Manager ...");
LifeCycleUtils.closeQuietly(this.globalEndpointManager);
logger.info("Closing StoreClientFactory ...");
LifeCycleUtils.closeQuietly(this.storeClientFactory);
logger.info("Shutting down reactorHttpClient ...");
LifeCycleUtils.closeQuietly(this.reactorHttpClient);
logger.info("Shutting down CpuMonitor ...");
CpuMemoryMonitor.unregister(this);
if (this.throughputControlEnabled.get()) {
logger.info("Closing ThroughputControlStore ...");
this.throughputControlStore.close();
}
logger.info("Shutting down completed.");
} else {
logger.warn("Already shutdown!");
}
}
@Override
public ItemDeserializer getItemDeserializer() {
return this.itemDeserializer;
}
@Override
public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group can not be null");
if (this.throughputControlEnabled.compareAndSet(false, true)) {
this.throughputControlStore =
new ThroughputControlStore(
this.collectionCache,
this.connectionPolicy.getConnectionMode(),
this.partitionKeyRangeCache);
this.storeModel.enableThroughputControl(throughputControlStore);
}
this.throughputControlStore.enableThroughputControlGroup(group);
}
private static SqlQuerySpec createLogicalPartitionScanQuerySpec(
PartitionKey partitionKey,
String partitionKeySelector) {
StringBuilder queryStringBuilder = new StringBuilder();
List<SqlParameter> parameters = new ArrayList<>();
queryStringBuilder.append("SELECT * FROM c WHERE");
Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey);
String pkParamName = "@pkValue";
parameters.add(new SqlParameter(pkParamName, pkValue));
queryStringBuilder.append(" c");
queryStringBuilder.append(partitionKeySelector);
queryStringBuilder.append((" = "));
queryStringBuilder.append(pkParamName);
return new SqlQuerySpec(queryStringBuilder.toString(), parameters);
}
@Override
public Mono<List<FeedRange>> getFeedRanges(String collectionLink) {
InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy(
this.collectionCache,
null,
collectionLink,
new HashMap<>());
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
this,
OperationType.Query,
ResourceType.Document,
collectionLink,
null);
invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request);
return ObservableHelper.inlineIfPossibleAsObs(
() -> getFeedRangesInternal(request, collectionLink),
invalidPartitionExceptionRetryPolicy);
}
private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) {
logger.debug("getFeedRange collectionLink=[{}]", collectionLink);
if (StringUtils.isEmpty(collectionLink)) {
throw new IllegalArgumentException("collectionLink");
}
Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null,
request);
return collectionObs.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache
.tryGetOverlappingRangesAsync(
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics),
collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null);
return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request));
});
}
private static List<FeedRange> toFeedRanges(
Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) {
final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v;
if (partitionKeyRangeList == null) {
request.forceNameCacheRefresh = true;
throw new InvalidPartitionException();
}
List<FeedRange> feedRanges = new ArrayList<>();
partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange)));
return feedRanges;
}
private static FeedRange toFeedRange(PartitionKeyRange pkRange) {
return new FeedRangeEpkImpl(pkRange.toRange());
}
} |
Not necessary - the request never leaves the machine - it is hosted on an endpoint similar to 127.0.01 - guaranteed to be on local machine. | private void loadAzureVmMetaData() {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null) {
this.populateAzureVmMetaData(metadataSnapshot);
return;
}
URI targetEndpoint = null;
try {
targetEndpoint = new URI(AZURE_VM_METADATA);
} catch (URISyntaxException ex) {
logger.info("Unable to parse azure vm metadata url");
return;
}
HashMap<String, String> headers = new HashMap<>();
headers.put("Metadata", "true");
HttpHeaders httpHeaders = new HttpHeaders(headers);
HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(),
httpHeaders);
Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest);
httpResponseMono
.flatMap(response -> response.bodyAsString()).map(metadataJson -> parse(metadataJson,
AzureVMMetadata.class)).doOnSuccess(metadata -> {
azureVmMetaDataSingleton.compareAndSet(null, metadata);
this.populateAzureVmMetaData(metadata);
}).onErrorResume(throwable -> {
logger.info("Client is not on azure vm");
logger.debug("Unable to get azure vm metadata", throwable);
return Mono.empty();
}).subscribe();
} | }).onErrorResume(throwable -> { | private void loadAzureVmMetaData() {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null) {
this.populateAzureVmMetaData(metadataSnapshot);
return;
}
URI targetEndpoint = null;
try {
targetEndpoint = new URI(AZURE_VM_METADATA);
} catch (URISyntaxException ex) {
logger.info("Unable to parse azure vm metadata url");
return;
}
HashMap<String, String> headers = new HashMap<>();
headers.put("Metadata", "true");
HttpHeaders httpHeaders = new HttpHeaders(headers);
HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(),
httpHeaders);
Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest);
httpResponseMono
.flatMap(response -> response.bodyAsString()).map(metadataJson -> parse(metadataJson,
AzureVMMetadata.class)).doOnSuccess(metadata -> {
azureVmMetaDataSingleton.compareAndSet(null, metadata);
this.populateAzureVmMetaData(metadata);
}).onErrorResume(throwable -> {
logger.info("Client is not on azure vm");
logger.debug("Unable to get azure vm metadata", throwable);
return Mono.empty();
}).subscribe();
} | class ClientTelemetry {
public final static int ONE_KB_TO_BYTES = 1024;
public final static int REQUEST_LATENCY_MAX_MILLI_SEC = 300000;
public final static int REQUEST_LATENCY_SUCCESS_PRECISION = 4;
public final static int REQUEST_LATENCY_FAILURE_PRECISION = 2;
public final static String REQUEST_LATENCY_NAME = "RequestLatency";
public final static String REQUEST_LATENCY_UNIT = "MilliSecond";
public final static int REQUEST_CHARGE_MAX = 10000;
public final static int REQUEST_CHARGE_PRECISION = 2;
public final static String REQUEST_CHARGE_NAME = "RequestCharge";
public final static String REQUEST_CHARGE_UNIT = "RU";
public final static String TCP_NEW_CHANNEL_LATENCY_NAME = "TcpNewChannelOpenLatency";
public final static String TCP_NEW_CHANNEL_LATENCY_UNIT = "MilliSecond";
public final static int TCP_NEW_CHANNEL_LATENCY_MAX_MILLI_SEC = 300000;
public final static int TCP_NEW_CHANNEL_LATENCY_PRECISION = 2;
public final static int CPU_MAX = 100;
public final static int CPU_PRECISION = 2;
private final static String CPU_NAME = "CPU";
private final static String CPU_UNIT = "Percentage";
public final static int MEMORY_MAX_IN_MB = 102400;
public final static int MEMORY_PRECISION = 2;
private final static String MEMORY_NAME = "MemoryRemaining";
private final static String MEMORY_UNIT = "MB";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final static AtomicLong instanceCount = new AtomicLong(0);
private final static AtomicReference<AzureVMMetadata> azureVmMetaDataSingleton =
new AtomicReference<>(null);
private ClientTelemetryInfo clientTelemetryInfo;
private final HttpClient httpClient;
private final ScheduledThreadPoolExecutor scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
new CosmosDaemonThreadFactory("ClientTelemetry-" + instanceCount.incrementAndGet()));
private final Scheduler scheduler = Schedulers.fromExecutor(scheduledExecutorService);
private static final Logger logger = LoggerFactory.getLogger(ClientTelemetry.class);
private volatile boolean isClosed;
private volatile boolean isClientTelemetryEnabled;
private static String AZURE_VM_METADATA = "http:
private static final double PERCENTILE_50 = 50.0;
private static final double PERCENTILE_90 = 90.0;
private static final double PERCENTILE_95 = 95.0;
private static final double PERCENTILE_99 = 99.0;
private static final double PERCENTILE_999 = 99.9;
private final int clientTelemetrySchedulingSec;
private final IAuthorizationTokenProvider tokenProvider;
private final String globalDatabaseAccountName;
public ClientTelemetry(DiagnosticsClientContext diagnosticsClientContext,
Boolean acceleratedNetworking,
String clientId,
String processId,
String userAgent,
ConnectionMode connectionMode,
String globalDatabaseAccountName,
String applicationRegion,
String hostEnvInfo,
HttpClient httpClient,
boolean isClientTelemetryEnabled,
IAuthorizationTokenProvider tokenProvider,
List<String> preferredRegions
) {
clientTelemetryInfo = new ClientTelemetryInfo(
getMachineId(diagnosticsClientContext),
clientId,
processId,
userAgent,
connectionMode,
globalDatabaseAccountName,
applicationRegion,
hostEnvInfo,
acceleratedNetworking,
preferredRegions);
this.isClosed = false;
this.httpClient = httpClient;
this.isClientTelemetryEnabled = isClientTelemetryEnabled;
this.clientTelemetrySchedulingSec = Configs.getClientTelemetrySchedulingInSec();
this.tokenProvider = tokenProvider;
this.globalDatabaseAccountName = globalDatabaseAccountName;
}
public ClientTelemetryInfo getClientTelemetryInfo() {
return clientTelemetryInfo;
}
public static String getMachineId(DiagnosticsClientContext diagnosticsClientContext) {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null && metadataSnapshot.getVmId() != null) {
String machineId = "vmId:" + metadataSnapshot.getVmId();
if (diagnosticsClientContext != null) {
diagnosticsClientContext.getConfig().withMachineId(machineId);
}
return machineId;
}
if (diagnosticsClientContext == null) {
return "";
}
return diagnosticsClientContext.getConfig().getMachineId();
}
public static void recordValue(ConcurrentDoubleHistogram doubleHistogram, long value) {
try {
doubleHistogram.recordValue(value);
} catch (Exception ex) {
logger.warn("Error while recording value for client telemetry. ", ex);
}
}
public static void recordValue(ConcurrentDoubleHistogram doubleHistogram, double value) {
try {
doubleHistogram.recordValue(value);
} catch (Exception ex) {
logger.warn("Error while recording value for client telemetry. ", ex);
}
}
public boolean isClientTelemetryEnabled() {
return isClientTelemetryEnabled;
}
public void init() {
loadAzureVmMetaData();
sendClientTelemetry().subscribe();
}
public void close() {
this.isClosed = true;
this.scheduledExecutorService.shutdown();
logger.debug("GlobalEndpointManager closed.");
}
private Mono<Void> sendClientTelemetry() {
return Mono.delay(Duration.ofSeconds(clientTelemetrySchedulingSec), CosmosSchedulers.COSMOS_PARALLEL)
.flatMap(t -> {
if (this.isClosed) {
logger.warn("client already closed");
return Mono.empty();
}
if (!Configs.isClientTelemetryEnabled(this.isClientTelemetryEnabled)) {
logger.trace("client telemetry not enabled");
return Mono.empty();
}
readHistogram();
try {
String endpoint = Configs.getClientTelemetryEndpoint();
if (StringUtils.isEmpty(endpoint)) {
logger.info("ClientTelemetry {}",
OBJECT_MAPPER.writeValueAsString(this.clientTelemetryInfo));
clearDataForNextRun();
return this.sendClientTelemetry();
} else {
URI targetEndpoint = new URI(endpoint);
ByteBuffer byteBuffer =
BridgeInternal.serializeJsonToByteBuffer(this.clientTelemetryInfo,
ClientTelemetry.OBJECT_MAPPER);
Flux<byte[]> fluxBytes = Flux.just(RxDocumentServiceRequest.toByteArray(byteBuffer));
Map<String, String> headers = new HashMap<>();
String date = Utils.nowAsRFC1123();
headers.put(HttpConstants.HttpHeaders.X_DATE, date);
String authorization = this.tokenProvider.getUserAuthorizationToken(
"", ResourceType.ClientTelemetry, RequestVerb.POST, headers,
AuthorizationTokenType.PrimaryMasterKey, null);
try {
authorization = URLEncoder.encode(authorization, Constants.UrlEncodingInfo.UTF_8);
} catch (UnsupportedEncodingException e) {
logger.error("Failed to encode authToken. Exception: ", e);
this.clearDataForNextRun();
return this.sendClientTelemetry();
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
httpHeaders.set(HttpConstants.HttpHeaders.CONTENT_ENCODING, RuntimeConstants.Encoding.GZIP);
httpHeaders.set(HttpConstants.HttpHeaders.X_DATE, date);
httpHeaders.set(HttpConstants.HttpHeaders.DATABASE_ACCOUNT_NAME,
this.globalDatabaseAccountName);
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
String envName = Configs.getEnvironmentName();
if (StringUtils.isNotEmpty(envName)) {
httpHeaders.set(HttpConstants.HttpHeaders.ENVIRONMENT_NAME, envName);
}
HttpRequest httpRequest = new HttpRequest(HttpMethod.POST, targetEndpoint,
targetEndpoint.getPort(), httpHeaders, fluxBytes);
Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest,
Duration.ofSeconds(Configs.getHttpResponseTimeoutInSeconds()));
return httpResponseMono.flatMap(response -> {
if (response.statusCode() != HttpConstants.StatusCodes.OK) {
logger.error("Client telemetry request did not succeeded, status code {}",
response.statusCode());
}
this.clearDataForNextRun();
return this.sendClientTelemetry();
}).onErrorResume(throwable -> {
logger.error("Error while sending client telemetry request Exception: ", throwable);
this.clearDataForNextRun();
return this.sendClientTelemetry();
});
}
} catch (JsonProcessingException | URISyntaxException ex) {
logger.error("Error while preparing client telemetry. Exception: ", ex);
this.clearDataForNextRun();
return this.sendClientTelemetry();
}
}).onErrorResume(ex -> {
logger.error("sendClientTelemetry() - Unable to send client telemetry" +
". Exception: ", ex);
clearDataForNextRun();
return this.sendClientTelemetry();
}).subscribeOn(scheduler);
}
private void populateAzureVmMetaData(AzureVMMetadata azureVMMetadata) {
this.clientTelemetryInfo.setApplicationRegion(azureVMMetadata.getLocation());
this.clientTelemetryInfo.setMachineId("vmId:" + azureVMMetadata.getVmId());
this.clientTelemetryInfo.setHostEnvInfo(azureVMMetadata.getOsType() + "|" + azureVMMetadata.getSku() +
"|" + azureVMMetadata.getVmSize() + "|" + azureVMMetadata.getAzEnvironment());
}
private static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) {
try {
return OBJECT_MAPPER.readValue(itemResponseBodyAsString, itemClassType);
} catch (IOException e) {
throw new IllegalStateException(
"Failed to parse string [" + itemResponseBodyAsString + "] to POJO.", e);
}
}
private void clearDataForNextRun() {
this.clientTelemetryInfo.getSystemInfoMap().clear();
this.clientTelemetryInfo.getOperationInfoMap().clear();
this.clientTelemetryInfo.getCacheRefreshInfoMap().clear();
for (ConcurrentDoubleHistogram histogram : this.clientTelemetryInfo.getSystemInfoMap().values()) {
histogram.reset();
}
}
private void readHistogram() {
ConcurrentDoubleHistogram cpuHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.CPU_MAX,
ClientTelemetry.CPU_PRECISION);
cpuHistogram.setAutoResize(true);
for (double val : CpuMemoryMonitor.getClientTelemetryCpuLatestList()) {
recordValue(cpuHistogram, val);
}
ReportPayload cpuReportPayload = new ReportPayload(CPU_NAME, CPU_UNIT);
clientTelemetryInfo.getSystemInfoMap().put(cpuReportPayload, cpuHistogram);
ConcurrentDoubleHistogram memoryHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.MEMORY_MAX_IN_MB,
ClientTelemetry.MEMORY_PRECISION);
memoryHistogram.setAutoResize(true);
for (double val : CpuMemoryMonitor.getClientTelemetryMemoryLatestList()) {
recordValue(memoryHistogram, val);
}
ReportPayload memoryReportPayload = new ReportPayload(MEMORY_NAME, MEMORY_UNIT);
clientTelemetryInfo.getSystemInfoMap().put(memoryReportPayload, memoryHistogram);
this.clientTelemetryInfo.setTimeStamp(Instant.now().toString());
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getSystemInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getCacheRefreshInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getOperationInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
}
private void fillMetricsInfo(ReportPayload payload, ConcurrentDoubleHistogram histogram) {
DoubleHistogram copyHistogram = histogram.copy();
payload.getMetricInfo().setCount(copyHistogram.getTotalCount());
payload.getMetricInfo().setMax(copyHistogram.getMaxValue());
payload.getMetricInfo().setMin(copyHistogram.getMinValue());
payload.getMetricInfo().setMean(copyHistogram.getMean());
Map<Double, Double> percentile = new HashMap<>();
percentile.put(PERCENTILE_50, copyHistogram.getValueAtPercentile(PERCENTILE_50));
percentile.put(PERCENTILE_90, copyHistogram.getValueAtPercentile(PERCENTILE_90));
percentile.put(PERCENTILE_95, copyHistogram.getValueAtPercentile(PERCENTILE_95));
percentile.put(PERCENTILE_99, copyHistogram.getValueAtPercentile(PERCENTILE_99));
percentile.put(PERCENTILE_999, copyHistogram.getValueAtPercentile(PERCENTILE_999));
payload.getMetricInfo().setPercentiles(percentile);
}
} | class ClientTelemetry {
public final static int ONE_KB_TO_BYTES = 1024;
public final static int REQUEST_LATENCY_MAX_MILLI_SEC = 300000;
public final static int REQUEST_LATENCY_SUCCESS_PRECISION = 4;
public final static int REQUEST_LATENCY_FAILURE_PRECISION = 2;
public final static String REQUEST_LATENCY_NAME = "RequestLatency";
public final static String REQUEST_LATENCY_UNIT = "MilliSecond";
public final static int REQUEST_CHARGE_MAX = 10000;
public final static int REQUEST_CHARGE_PRECISION = 2;
public final static String REQUEST_CHARGE_NAME = "RequestCharge";
public final static String REQUEST_CHARGE_UNIT = "RU";
public final static String TCP_NEW_CHANNEL_LATENCY_NAME = "TcpNewChannelOpenLatency";
public final static String TCP_NEW_CHANNEL_LATENCY_UNIT = "MilliSecond";
public final static int TCP_NEW_CHANNEL_LATENCY_MAX_MILLI_SEC = 300000;
public final static int TCP_NEW_CHANNEL_LATENCY_PRECISION = 2;
public final static int CPU_MAX = 100;
public final static int CPU_PRECISION = 2;
private final static String CPU_NAME = "CPU";
private final static String CPU_UNIT = "Percentage";
public final static int MEMORY_MAX_IN_MB = 102400;
public final static int MEMORY_PRECISION = 2;
private final static String MEMORY_NAME = "MemoryRemaining";
private final static String MEMORY_UNIT = "MB";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final static AtomicLong instanceCount = new AtomicLong(0);
private final static AtomicReference<AzureVMMetadata> azureVmMetaDataSingleton =
new AtomicReference<>(null);
private ClientTelemetryInfo clientTelemetryInfo;
private final HttpClient httpClient;
private final ScheduledThreadPoolExecutor scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
new CosmosDaemonThreadFactory("ClientTelemetry-" + instanceCount.incrementAndGet()));
private final Scheduler scheduler = Schedulers.fromExecutor(scheduledExecutorService);
private static final Logger logger = LoggerFactory.getLogger(ClientTelemetry.class);
private volatile boolean isClosed;
private volatile boolean isClientTelemetryEnabled;
private static String AZURE_VM_METADATA = "http:
private static final double PERCENTILE_50 = 50.0;
private static final double PERCENTILE_90 = 90.0;
private static final double PERCENTILE_95 = 95.0;
private static final double PERCENTILE_99 = 99.0;
private static final double PERCENTILE_999 = 99.9;
private final int clientTelemetrySchedulingSec;
private final IAuthorizationTokenProvider tokenProvider;
private final String globalDatabaseAccountName;
public ClientTelemetry(DiagnosticsClientContext diagnosticsClientContext,
Boolean acceleratedNetworking,
String clientId,
String processId,
String userAgent,
ConnectionMode connectionMode,
String globalDatabaseAccountName,
String applicationRegion,
String hostEnvInfo,
HttpClient httpClient,
boolean isClientTelemetryEnabled,
IAuthorizationTokenProvider tokenProvider,
List<String> preferredRegions
) {
clientTelemetryInfo = new ClientTelemetryInfo(
getMachineId(diagnosticsClientContext),
clientId,
processId,
userAgent,
connectionMode,
globalDatabaseAccountName,
applicationRegion,
hostEnvInfo,
acceleratedNetworking,
preferredRegions);
this.isClosed = false;
this.httpClient = httpClient;
this.isClientTelemetryEnabled = isClientTelemetryEnabled;
this.clientTelemetrySchedulingSec = Configs.getClientTelemetrySchedulingInSec();
this.tokenProvider = tokenProvider;
this.globalDatabaseAccountName = globalDatabaseAccountName;
}
public ClientTelemetryInfo getClientTelemetryInfo() {
return clientTelemetryInfo;
}
public static String getMachineId(DiagnosticsClientContext diagnosticsClientContext) {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null && metadataSnapshot.getVmId() != null) {
String machineId = "vmId:" + metadataSnapshot.getVmId();
if (diagnosticsClientContext != null) {
diagnosticsClientContext.getConfig().withMachineId(machineId);
}
return machineId;
}
if (diagnosticsClientContext == null) {
return "";
}
return diagnosticsClientContext.getConfig().getMachineId();
}
public static void recordValue(ConcurrentDoubleHistogram doubleHistogram, long value) {
try {
doubleHistogram.recordValue(value);
} catch (Exception ex) {
logger.warn("Error while recording value for client telemetry. ", ex);
}
}
public static void recordValue(ConcurrentDoubleHistogram doubleHistogram, double value) {
try {
doubleHistogram.recordValue(value);
} catch (Exception ex) {
logger.warn("Error while recording value for client telemetry. ", ex);
}
}
public boolean isClientTelemetryEnabled() {
return isClientTelemetryEnabled;
}
public void init() {
loadAzureVmMetaData();
sendClientTelemetry().subscribe();
}
public void close() {
this.isClosed = true;
this.scheduledExecutorService.shutdown();
logger.debug("GlobalEndpointManager closed.");
}
private Mono<Void> sendClientTelemetry() {
return Mono.delay(Duration.ofSeconds(clientTelemetrySchedulingSec), CosmosSchedulers.COSMOS_PARALLEL)
.flatMap(t -> {
if (this.isClosed) {
logger.warn("client already closed");
return Mono.empty();
}
if (!Configs.isClientTelemetryEnabled(this.isClientTelemetryEnabled)) {
logger.trace("client telemetry not enabled");
return Mono.empty();
}
readHistogram();
try {
String endpoint = Configs.getClientTelemetryEndpoint();
if (StringUtils.isEmpty(endpoint)) {
logger.info("ClientTelemetry {}",
OBJECT_MAPPER.writeValueAsString(this.clientTelemetryInfo));
clearDataForNextRun();
return this.sendClientTelemetry();
} else {
URI targetEndpoint = new URI(endpoint);
ByteBuffer byteBuffer =
BridgeInternal.serializeJsonToByteBuffer(this.clientTelemetryInfo,
ClientTelemetry.OBJECT_MAPPER);
Flux<byte[]> fluxBytes = Flux.just(RxDocumentServiceRequest.toByteArray(byteBuffer));
Map<String, String> headers = new HashMap<>();
String date = Utils.nowAsRFC1123();
headers.put(HttpConstants.HttpHeaders.X_DATE, date);
String authorization = this.tokenProvider.getUserAuthorizationToken(
"", ResourceType.ClientTelemetry, RequestVerb.POST, headers,
AuthorizationTokenType.PrimaryMasterKey, null);
try {
authorization = URLEncoder.encode(authorization, Constants.UrlEncodingInfo.UTF_8);
} catch (UnsupportedEncodingException e) {
logger.error("Failed to encode authToken. Exception: ", e);
this.clearDataForNextRun();
return this.sendClientTelemetry();
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
httpHeaders.set(HttpConstants.HttpHeaders.CONTENT_ENCODING, RuntimeConstants.Encoding.GZIP);
httpHeaders.set(HttpConstants.HttpHeaders.X_DATE, date);
httpHeaders.set(HttpConstants.HttpHeaders.DATABASE_ACCOUNT_NAME,
this.globalDatabaseAccountName);
httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization);
String envName = Configs.getEnvironmentName();
if (StringUtils.isNotEmpty(envName)) {
httpHeaders.set(HttpConstants.HttpHeaders.ENVIRONMENT_NAME, envName);
}
HttpRequest httpRequest = new HttpRequest(HttpMethod.POST, targetEndpoint,
targetEndpoint.getPort(), httpHeaders, fluxBytes);
Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest,
Duration.ofSeconds(Configs.getHttpResponseTimeoutInSeconds()));
return httpResponseMono.flatMap(response -> {
if (response.statusCode() != HttpConstants.StatusCodes.OK) {
logger.error("Client telemetry request did not succeeded, status code {}",
response.statusCode());
}
this.clearDataForNextRun();
return this.sendClientTelemetry();
}).onErrorResume(throwable -> {
logger.error("Error while sending client telemetry request Exception: ", throwable);
this.clearDataForNextRun();
return this.sendClientTelemetry();
});
}
} catch (JsonProcessingException | URISyntaxException ex) {
logger.error("Error while preparing client telemetry. Exception: ", ex);
this.clearDataForNextRun();
return this.sendClientTelemetry();
}
}).onErrorResume(ex -> {
logger.error("sendClientTelemetry() - Unable to send client telemetry" +
". Exception: ", ex);
clearDataForNextRun();
return this.sendClientTelemetry();
}).subscribeOn(scheduler);
}
private void populateAzureVmMetaData(AzureVMMetadata azureVMMetadata) {
this.clientTelemetryInfo.setApplicationRegion(azureVMMetadata.getLocation());
this.clientTelemetryInfo.setMachineId("vmId:" + azureVMMetadata.getVmId());
this.clientTelemetryInfo.setHostEnvInfo(azureVMMetadata.getOsType() + "|" + azureVMMetadata.getSku() +
"|" + azureVMMetadata.getVmSize() + "|" + azureVMMetadata.getAzEnvironment());
}
private static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) {
try {
return OBJECT_MAPPER.readValue(itemResponseBodyAsString, itemClassType);
} catch (IOException e) {
throw new IllegalStateException(
"Failed to parse string [" + itemResponseBodyAsString + "] to POJO.", e);
}
}
private void clearDataForNextRun() {
this.clientTelemetryInfo.getSystemInfoMap().clear();
this.clientTelemetryInfo.getOperationInfoMap().clear();
this.clientTelemetryInfo.getCacheRefreshInfoMap().clear();
for (ConcurrentDoubleHistogram histogram : this.clientTelemetryInfo.getSystemInfoMap().values()) {
histogram.reset();
}
}
private void readHistogram() {
ConcurrentDoubleHistogram cpuHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.CPU_MAX,
ClientTelemetry.CPU_PRECISION);
cpuHistogram.setAutoResize(true);
for (double val : CpuMemoryMonitor.getClientTelemetryCpuLatestList()) {
recordValue(cpuHistogram, val);
}
ReportPayload cpuReportPayload = new ReportPayload(CPU_NAME, CPU_UNIT);
clientTelemetryInfo.getSystemInfoMap().put(cpuReportPayload, cpuHistogram);
ConcurrentDoubleHistogram memoryHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.MEMORY_MAX_IN_MB,
ClientTelemetry.MEMORY_PRECISION);
memoryHistogram.setAutoResize(true);
for (double val : CpuMemoryMonitor.getClientTelemetryMemoryLatestList()) {
recordValue(memoryHistogram, val);
}
ReportPayload memoryReportPayload = new ReportPayload(MEMORY_NAME, MEMORY_UNIT);
clientTelemetryInfo.getSystemInfoMap().put(memoryReportPayload, memoryHistogram);
this.clientTelemetryInfo.setTimeStamp(Instant.now().toString());
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getSystemInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getCacheRefreshInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
for (Map.Entry<ReportPayload, ConcurrentDoubleHistogram> entry :
this.clientTelemetryInfo.getOperationInfoMap().entrySet()) {
fillMetricsInfo(entry.getKey(), entry.getValue());
}
}
private void fillMetricsInfo(ReportPayload payload, ConcurrentDoubleHistogram histogram) {
DoubleHistogram copyHistogram = histogram.copy();
payload.getMetricInfo().setCount(copyHistogram.getTotalCount());
payload.getMetricInfo().setMax(copyHistogram.getMaxValue());
payload.getMetricInfo().setMin(copyHistogram.getMinValue());
payload.getMetricInfo().setMean(copyHistogram.getMean());
Map<Double, Double> percentile = new HashMap<>();
percentile.put(PERCENTILE_50, copyHistogram.getValueAtPercentile(PERCENTILE_50));
percentile.put(PERCENTILE_90, copyHistogram.getValueAtPercentile(PERCENTILE_90));
percentile.put(PERCENTILE_95, copyHistogram.getValueAtPercentile(PERCENTILE_95));
percentile.put(PERCENTILE_99, copyHistogram.getValueAtPercentile(PERCENTILE_99));
percentile.put(PERCENTILE_999, copyHistogram.getValueAtPercentile(PERCENTILE_999));
payload.getMetricInfo().setPercentiles(percentile);
}
} |
nit: this | public Set<ThroughputControlGroupInternal> getThroughputControlGroupSet() {
return throughputControlGroupSet;
} | return throughputControlGroupSet; | public Set<ThroughputControlGroupInternal> getThroughputControlGroupSet() {
return this.throughputControlGroupSet;
} | class ContainerThroughputControlGroupProperties {
private static Logger logger = LoggerFactory.getLogger(ContainerThroughputControlGroupProperties.class);
private final AtomicReference<ThroughputControlGroupInternal> defaultGroup;
private final Set<ThroughputControlGroupInternal> throughputControlGroupSet;
private final Set<String> supressInitErrorGroupSet;
public ContainerThroughputControlGroupProperties() {
this.defaultGroup = new AtomicReference<>();
this.throughputControlGroupSet = ConcurrentHashMap.newKeySet();
this.supressInitErrorGroupSet = ConcurrentHashMap.newKeySet();
}
public int addThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group should not be null");
if (group.isDefault()) {
if (!this.defaultGroup.compareAndSet(null, group)) {
if (!this.defaultGroup.get().equals(group)) {
throw new IllegalStateException("A default group already exists");
}
}
}
if (group.isSuppressInitError()) {
this.supressInitErrorGroupSet.add(group.getGroupName());
}
if (this.throughputControlGroupSet.stream()
.anyMatch(existingGroup -> StringUtils.equals(existingGroup.getId(), group.getId()) && !existingGroup.equals(group))) {
throw new IllegalStateException("Throughput control group with id " + group.getId() + " already exists");
}
this.throughputControlGroupSet.add(group);
return this.throughputControlGroupSet.size();
}
public boolean allowRequestContinueOnInitError(RxDocumentServiceRequest request) {
checkNotNull(request, "Request should not be null");
String requestGroupName = request.getThroughputControlGroupName();
if (StringUtils.isEmpty(requestGroupName)) {
requestGroupName = this.defaultGroup.get().getGroupName();
}
return this.supressInitErrorGroupSet.contains(requestGroupName);
}
} | class ContainerThroughputControlGroupProperties {
private static Logger logger = LoggerFactory.getLogger(ContainerThroughputControlGroupProperties.class);
private final AtomicReference<ThroughputControlGroupInternal> defaultGroup;
private final Set<ThroughputControlGroupInternal> throughputControlGroupSet;
private final Set<String> supressInitErrorGroupSet;
public ContainerThroughputControlGroupProperties() {
this.defaultGroup = new AtomicReference<>();
this.throughputControlGroupSet = ConcurrentHashMap.newKeySet();
this.supressInitErrorGroupSet = ConcurrentHashMap.newKeySet();
}
/***
* Enable a throughput control group.
*
* @param group a {@link ThroughputControlGroupInternal}.
*
* @return the total size of distinct throughput control groups enabled on the container.
*/
public int enableThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group should not be null");
if (group.isDefault()) {
if (!this.defaultGroup.compareAndSet(null, group)) {
if (!this.defaultGroup.get().equals(group)) {
throw new IllegalArgumentException("A default group already exists");
}
}
}
if (group.isContinueOnInitError()) {
this.supressInitErrorGroupSet.add(group.getGroupName());
}
if (this.throughputControlGroupSet.stream()
.anyMatch(existingGroup -> Objects.equals(existingGroup.getId(), group.getId()) && !existingGroup.equals(group))) {
throw new IllegalArgumentException("Throughput control group with id " + group.getId() + " already exists");
}
this.throughputControlGroupSet.add(group);
return this.throughputControlGroupSet.size();
}
public boolean allowRequestToContinueOnInitError(RxDocumentServiceRequest request) {
checkNotNull(request, "Request should not be null");
String requestGroupName = request.getThroughputControlGroupName();
if (StringUtils.isEmpty(requestGroupName)) {
requestGroupName = this.defaultGroup.get().getGroupName();
}
return this.supressInitErrorGroupSet.contains(requestGroupName);
}
} |
Interesting you used `ConcurrentHashMap.newKeySet()` instead of `Collections.synchronizedSet(new HashSet<>());` I am curious to learn, any specific reason for using this? | public ContainerThroughputControlGroupProperties() {
this.defaultGroup = new AtomicReference<>();
this.throughputControlGroupSet = ConcurrentHashMap.newKeySet();
this.supressInitErrorGroupSet = ConcurrentHashMap.newKeySet();
} | this.throughputControlGroupSet = ConcurrentHashMap.newKeySet(); | public ContainerThroughputControlGroupProperties() {
this.defaultGroup = new AtomicReference<>();
this.throughputControlGroupSet = ConcurrentHashMap.newKeySet();
this.supressInitErrorGroupSet = ConcurrentHashMap.newKeySet();
} | class ContainerThroughputControlGroupProperties {
private static Logger logger = LoggerFactory.getLogger(ContainerThroughputControlGroupProperties.class);
private final AtomicReference<ThroughputControlGroupInternal> defaultGroup;
private final Set<ThroughputControlGroupInternal> throughputControlGroupSet;
private final Set<String> supressInitErrorGroupSet;
public int addThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group should not be null");
if (group.isDefault()) {
if (!this.defaultGroup.compareAndSet(null, group)) {
if (!this.defaultGroup.get().equals(group)) {
throw new IllegalArgumentException("A default group already exists");
}
}
}
if (group.isContinueOnInitError()) {
this.supressInitErrorGroupSet.add(group.getGroupName());
}
if (this.throughputControlGroupSet.stream()
.anyMatch(existingGroup -> StringUtils.equals(existingGroup.getId(), group.getId()) && !existingGroup.equals(group))) {
throw new IllegalArgumentException("Throughput control group with id " + group.getId() + " already exists");
}
this.throughputControlGroupSet.add(group);
return this.throughputControlGroupSet.size();
}
public Set<ThroughputControlGroupInternal> getThroughputControlGroupSet() {
return this.throughputControlGroupSet;
}
public boolean allowRequestToContinueOnInitError(RxDocumentServiceRequest request) {
checkNotNull(request, "Request should not be null");
String requestGroupName = request.getThroughputControlGroupName();
if (StringUtils.isEmpty(requestGroupName)) {
requestGroupName = this.defaultGroup.get().getGroupName();
}
return this.supressInitErrorGroupSet.contains(requestGroupName);
}
} | class ContainerThroughputControlGroupProperties {
private static Logger logger = LoggerFactory.getLogger(ContainerThroughputControlGroupProperties.class);
private final AtomicReference<ThroughputControlGroupInternal> defaultGroup;
private final Set<ThroughputControlGroupInternal> throughputControlGroupSet;
private final Set<String> supressInitErrorGroupSet;
/***
* Enable a throughput control group.
*
* @param group a {@link ThroughputControlGroupInternal}.
*
* @return the total size of distinct throughput control groups enabled on the container.
*/
public int enableThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group should not be null");
if (group.isDefault()) {
if (!this.defaultGroup.compareAndSet(null, group)) {
if (!this.defaultGroup.get().equals(group)) {
throw new IllegalArgumentException("A default group already exists");
}
}
}
if (group.isContinueOnInitError()) {
this.supressInitErrorGroupSet.add(group.getGroupName());
}
if (this.throughputControlGroupSet.stream()
.anyMatch(existingGroup -> Objects.equals(existingGroup.getId(), group.getId()) && !existingGroup.equals(group))) {
throw new IllegalArgumentException("Throughput control group with id " + group.getId() + " already exists");
}
this.throughputControlGroupSet.add(group);
return this.throughputControlGroupSet.size();
}
public Set<ThroughputControlGroupInternal> getThroughputControlGroupSet() {
return this.throughputControlGroupSet;
}
public boolean allowRequestToContinueOnInitError(RxDocumentServiceRequest request) {
checkNotNull(request, "Request should not be null");
String requestGroupName = request.getThroughputControlGroupName();
if (StringUtils.isEmpty(requestGroupName)) {
requestGroupName = this.defaultGroup.get().getGroupName();
}
return this.supressInitErrorGroupSet.contains(requestGroupName);
}
} |
My understanding is for Collections.synchronizedSet, it is more like a wrapper around the whole set. For each operation in the original set, it wrapped with Synchronized keyword. | public ContainerThroughputControlGroupProperties() {
this.defaultGroup = new AtomicReference<>();
this.throughputControlGroupSet = ConcurrentHashMap.newKeySet();
this.supressInitErrorGroupSet = ConcurrentHashMap.newKeySet();
} | this.throughputControlGroupSet = ConcurrentHashMap.newKeySet(); | public ContainerThroughputControlGroupProperties() {
this.defaultGroup = new AtomicReference<>();
this.throughputControlGroupSet = ConcurrentHashMap.newKeySet();
this.supressInitErrorGroupSet = ConcurrentHashMap.newKeySet();
} | class ContainerThroughputControlGroupProperties {
private static Logger logger = LoggerFactory.getLogger(ContainerThroughputControlGroupProperties.class);
private final AtomicReference<ThroughputControlGroupInternal> defaultGroup;
private final Set<ThroughputControlGroupInternal> throughputControlGroupSet;
private final Set<String> supressInitErrorGroupSet;
public int addThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group should not be null");
if (group.isDefault()) {
if (!this.defaultGroup.compareAndSet(null, group)) {
if (!this.defaultGroup.get().equals(group)) {
throw new IllegalArgumentException("A default group already exists");
}
}
}
if (group.isContinueOnInitError()) {
this.supressInitErrorGroupSet.add(group.getGroupName());
}
if (this.throughputControlGroupSet.stream()
.anyMatch(existingGroup -> StringUtils.equals(existingGroup.getId(), group.getId()) && !existingGroup.equals(group))) {
throw new IllegalArgumentException("Throughput control group with id " + group.getId() + " already exists");
}
this.throughputControlGroupSet.add(group);
return this.throughputControlGroupSet.size();
}
public Set<ThroughputControlGroupInternal> getThroughputControlGroupSet() {
return this.throughputControlGroupSet;
}
public boolean allowRequestToContinueOnInitError(RxDocumentServiceRequest request) {
checkNotNull(request, "Request should not be null");
String requestGroupName = request.getThroughputControlGroupName();
if (StringUtils.isEmpty(requestGroupName)) {
requestGroupName = this.defaultGroup.get().getGroupName();
}
return this.supressInitErrorGroupSet.contains(requestGroupName);
}
} | class ContainerThroughputControlGroupProperties {
private static Logger logger = LoggerFactory.getLogger(ContainerThroughputControlGroupProperties.class);
private final AtomicReference<ThroughputControlGroupInternal> defaultGroup;
private final Set<ThroughputControlGroupInternal> throughputControlGroupSet;
private final Set<String> supressInitErrorGroupSet;
/***
* Enable a throughput control group.
*
* @param group a {@link ThroughputControlGroupInternal}.
*
* @return the total size of distinct throughput control groups enabled on the container.
*/
public int enableThroughputControlGroup(ThroughputControlGroupInternal group) {
checkNotNull(group, "Throughput control group should not be null");
if (group.isDefault()) {
if (!this.defaultGroup.compareAndSet(null, group)) {
if (!this.defaultGroup.get().equals(group)) {
throw new IllegalArgumentException("A default group already exists");
}
}
}
if (group.isContinueOnInitError()) {
this.supressInitErrorGroupSet.add(group.getGroupName());
}
if (this.throughputControlGroupSet.stream()
.anyMatch(existingGroup -> Objects.equals(existingGroup.getId(), group.getId()) && !existingGroup.equals(group))) {
throw new IllegalArgumentException("Throughput control group with id " + group.getId() + " already exists");
}
this.throughputControlGroupSet.add(group);
return this.throughputControlGroupSet.size();
}
public Set<ThroughputControlGroupInternal> getThroughputControlGroupSet() {
return this.throughputControlGroupSet;
}
public boolean allowRequestToContinueOnInitError(RxDocumentServiceRequest request) {
checkNotNull(request, "Request should not be null");
String requestGroupName = request.getThroughputControlGroupName();
if (StringUtils.isEmpty(requestGroupName)) {
requestGroupName = this.defaultGroup.get().getGroupName();
}
return this.supressInitErrorGroupSet.contains(requestGroupName);
}
} |
please help change to `spring-cloud-azure-not-existing-xx` | protected void doHealthCheck(Health.Builder builder) {
try {
this.secretAsyncClient.getSecretWithResponse("spring-cloud-azure-none-existing-secret", "")
.block(timeout);
builder.up();
} catch (Exception e) {
if (e instanceof ResourceNotFoundException) {
builder.up();
} else {
throw e;
}
}
} | this.secretAsyncClient.getSecretWithResponse("spring-cloud-azure-none-existing-secret", "") | protected void doHealthCheck(Health.Builder builder) {
try {
this.secretAsyncClient.getSecretWithResponse("spring-cloud-azure-not-existing-secret", "")
.block(timeout);
builder.up();
} catch (Exception e) {
if (e instanceof ResourceNotFoundException) {
builder.up();
} else {
throw e;
}
}
} | class KeyVaultSecretHealthIndicator extends AbstractHealthIndicator {
private final SecretAsyncClient secretAsyncClient;
private Duration timeout = DEFAULT_HEALTH_CHECK_TIMEOUT;
/**
* Creates a new instance of {@link KeyVaultSecretHealthIndicator}.
* @param secretAsyncClient the secret async client
*/
public KeyVaultSecretHealthIndicator(SecretAsyncClient secretAsyncClient) {
this.secretAsyncClient = secretAsyncClient;
}
@Override
/**
* Set health check request timeout.
* @param timeout the duration value.
*/
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
} | class KeyVaultSecretHealthIndicator extends AbstractHealthIndicator {
private final SecretAsyncClient secretAsyncClient;
private Duration timeout = DEFAULT_HEALTH_CHECK_TIMEOUT;
/**
* Creates a new instance of {@link KeyVaultSecretHealthIndicator}.
* @param secretAsyncClient the secret async client
*/
public KeyVaultSecretHealthIndicator(SecretAsyncClient secretAsyncClient) {
this.secretAsyncClient = secretAsyncClient;
}
@Override
/**
* Set health check request timeout.
* @param timeout the duration value.
*/
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
} |
It's weird that this feature is partly contained in the library. | protected void configure(HttpSecurity http) throws Exception {
http.oauth2Login()
.authorizationEndpoint()
.authorizationRequestResolver(requestResolver())
.and()
.tokenEndpoint()
.accessTokenResponseClient(accessTokenResponseClient())
.and()
.userInfoEndpoint()
.oidcUserService(oidcUserService)
.and()
.and()
.logout()
.logoutSuccessHandler(oidcLogoutSuccessHandler());
Filter handleConditionalAccessFilter = handleConditionalAccessFilter();
if (handleConditionalAccessFilter != null) {
http.addFilterAfter(handleConditionalAccessFilter, OAuth2AuthorizationRequestRedirectFilter.class);
}
} | http.addFilterAfter(handleConditionalAccessFilter, OAuth2AuthorizationRequestRedirectFilter.class); | protected void configure(HttpSecurity http) throws Exception {
http.oauth2Login()
.authorizationEndpoint()
.authorizationRequestResolver(requestResolver())
.and()
.tokenEndpoint()
.accessTokenResponseClient(accessTokenResponseClient())
.and()
.userInfoEndpoint()
.oidcUserService(oidcUserService)
.and()
.and()
.logout()
.logoutSuccessHandler(oidcLogoutSuccessHandler());
Filter conditionalAccessFilter = conditionalAccessFilter();
if (conditionalAccessFilter != null) {
http.addFilterAfter(conditionalAccessFilter, OAuth2AuthorizationRequestRedirectFilter.class);
}
} | class AadWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired
private ClientRegistrationRepository repo;
@Autowired
private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;
/**
* AAD authentication properties
*/
@Autowired
protected AadAuthenticationProperties properties;
/**
* configure
*
* @param http the {@link HttpSecurity} to use
* @throws Exception Configuration failed
*
*/
@Override
/**
* Return the filter to handle conditional access exception.
* No conditional access filter is provided by default.
* @return a filter that handles conditional access exception.
*/
protected Filter handleConditionalAccessFilter() {
return null;
}
/**
* Gets the OIDC logout success handler.
*
* @return the OIDC logout success handler
*/
protected LogoutSuccessHandler oidcLogoutSuccessHandler() {
OidcClientInitiatedLogoutSuccessHandler oidcLogoutSuccessHandler =
new OidcClientInitiatedLogoutSuccessHandler(this.repo);
String uri = this.properties.getPostLogoutRedirectUri();
if (StringUtils.hasText(uri)) {
oidcLogoutSuccessHandler.setPostLogoutRedirectUri(uri);
}
return oidcLogoutSuccessHandler;
}
/**
* Gets the access token response client.
*
* @return the access token response client
*/
protected OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() {
DefaultAuthorizationCodeTokenResponseClient result = new DefaultAuthorizationCodeTokenResponseClient();
if (repo instanceof AadClientRegistrationRepository) {
result.setRequestEntityConverter(
new AadOAuth2AuthorizationCodeGrantRequestEntityConverter(
((AadClientRegistrationRepository) repo).getAzureClientAccessTokenScopes()));
}
return result;
}
/**
* Gets the request resolver.
*
* @return the request resolver
*/
protected OAuth2AuthorizationRequestResolver requestResolver() {
return new AadOAuth2AuthorizationRequestResolver(this.repo, properties);
}
} | class AadWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired
private ClientRegistrationRepository repo;
@Autowired
private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;
/**
* AAD authentication properties
*/
@Autowired
protected AadAuthenticationProperties properties;
/**
* configure
*
* @param http the {@link HttpSecurity} to use
* @throws Exception Configuration failed
*
*/
@Override
/**
* Return the filter to handle conditional access exception.
* No conditional access filter is provided by default.
* @see <a href="https:
* @see <a href="https:
* @return a filter that handles conditional access exception.
*/
protected Filter conditionalAccessFilter() {
return null;
}
/**
* Gets the OIDC logout success handler.
*
* @return the OIDC logout success handler
*/
protected LogoutSuccessHandler oidcLogoutSuccessHandler() {
OidcClientInitiatedLogoutSuccessHandler oidcLogoutSuccessHandler =
new OidcClientInitiatedLogoutSuccessHandler(this.repo);
String uri = this.properties.getPostLogoutRedirectUri();
if (StringUtils.hasText(uri)) {
oidcLogoutSuccessHandler.setPostLogoutRedirectUri(uri);
}
return oidcLogoutSuccessHandler;
}
/**
* Gets the access token response client.
*
* @return the access token response client
*/
protected OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() {
DefaultAuthorizationCodeTokenResponseClient result = new DefaultAuthorizationCodeTokenResponseClient();
if (repo instanceof AadClientRegistrationRepository) {
result.setRequestEntityConverter(
new AadOAuth2AuthorizationCodeGrantRequestEntityConverter(
((AadClientRegistrationRepository) repo).getAzureClientAccessTokenScopes()));
}
return result;
}
/**
* Gets the request resolver.
*
* @return the request resolver
*/
protected OAuth2AuthorizationRequestResolver requestResolver() {
return new AadOAuth2AuthorizationRequestResolver(this.repo, properties);
}
} |
Yes, a little bit, maybe we will add back in the future. | protected void configure(HttpSecurity http) throws Exception {
http.oauth2Login()
.authorizationEndpoint()
.authorizationRequestResolver(requestResolver())
.and()
.tokenEndpoint()
.accessTokenResponseClient(accessTokenResponseClient())
.and()
.userInfoEndpoint()
.oidcUserService(oidcUserService)
.and()
.and()
.logout()
.logoutSuccessHandler(oidcLogoutSuccessHandler());
Filter handleConditionalAccessFilter = handleConditionalAccessFilter();
if (handleConditionalAccessFilter != null) {
http.addFilterAfter(handleConditionalAccessFilter, OAuth2AuthorizationRequestRedirectFilter.class);
}
} | http.addFilterAfter(handleConditionalAccessFilter, OAuth2AuthorizationRequestRedirectFilter.class); | protected void configure(HttpSecurity http) throws Exception {
http.oauth2Login()
.authorizationEndpoint()
.authorizationRequestResolver(requestResolver())
.and()
.tokenEndpoint()
.accessTokenResponseClient(accessTokenResponseClient())
.and()
.userInfoEndpoint()
.oidcUserService(oidcUserService)
.and()
.and()
.logout()
.logoutSuccessHandler(oidcLogoutSuccessHandler());
Filter conditionalAccessFilter = conditionalAccessFilter();
if (conditionalAccessFilter != null) {
http.addFilterAfter(conditionalAccessFilter, OAuth2AuthorizationRequestRedirectFilter.class);
}
} | class AadWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired
private ClientRegistrationRepository repo;
@Autowired
private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;
/**
* AAD authentication properties
*/
@Autowired
protected AadAuthenticationProperties properties;
/**
* configure
*
* @param http the {@link HttpSecurity} to use
* @throws Exception Configuration failed
*
*/
@Override
/**
* Return the filter to handle conditional access exception.
* No conditional access filter is provided by default.
* @return a filter that handles conditional access exception.
*/
protected Filter handleConditionalAccessFilter() {
return null;
}
/**
* Gets the OIDC logout success handler.
*
* @return the OIDC logout success handler
*/
protected LogoutSuccessHandler oidcLogoutSuccessHandler() {
OidcClientInitiatedLogoutSuccessHandler oidcLogoutSuccessHandler =
new OidcClientInitiatedLogoutSuccessHandler(this.repo);
String uri = this.properties.getPostLogoutRedirectUri();
if (StringUtils.hasText(uri)) {
oidcLogoutSuccessHandler.setPostLogoutRedirectUri(uri);
}
return oidcLogoutSuccessHandler;
}
/**
* Gets the access token response client.
*
* @return the access token response client
*/
protected OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() {
DefaultAuthorizationCodeTokenResponseClient result = new DefaultAuthorizationCodeTokenResponseClient();
if (repo instanceof AadClientRegistrationRepository) {
result.setRequestEntityConverter(
new AadOAuth2AuthorizationCodeGrantRequestEntityConverter(
((AadClientRegistrationRepository) repo).getAzureClientAccessTokenScopes()));
}
return result;
}
/**
* Gets the request resolver.
*
* @return the request resolver
*/
protected OAuth2AuthorizationRequestResolver requestResolver() {
return new AadOAuth2AuthorizationRequestResolver(this.repo, properties);
}
} | class AadWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired
private ClientRegistrationRepository repo;
@Autowired
private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;
/**
* AAD authentication properties
*/
@Autowired
protected AadAuthenticationProperties properties;
/**
* configure
*
* @param http the {@link HttpSecurity} to use
* @throws Exception Configuration failed
*
*/
@Override
/**
* Return the filter to handle conditional access exception.
* No conditional access filter is provided by default.
* @see <a href="https:
* @see <a href="https:
* @return a filter that handles conditional access exception.
*/
protected Filter conditionalAccessFilter() {
return null;
}
/**
* Gets the OIDC logout success handler.
*
* @return the OIDC logout success handler
*/
protected LogoutSuccessHandler oidcLogoutSuccessHandler() {
OidcClientInitiatedLogoutSuccessHandler oidcLogoutSuccessHandler =
new OidcClientInitiatedLogoutSuccessHandler(this.repo);
String uri = this.properties.getPostLogoutRedirectUri();
if (StringUtils.hasText(uri)) {
oidcLogoutSuccessHandler.setPostLogoutRedirectUri(uri);
}
return oidcLogoutSuccessHandler;
}
/**
* Gets the access token response client.
*
* @return the access token response client
*/
protected OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() {
DefaultAuthorizationCodeTokenResponseClient result = new DefaultAuthorizationCodeTokenResponseClient();
if (repo instanceof AadClientRegistrationRepository) {
result.setRequestEntityConverter(
new AadOAuth2AuthorizationCodeGrantRequestEntityConverter(
((AadClientRegistrationRepository) repo).getAzureClientAccessTokenScopes()));
}
return result;
}
/**
* Gets the request resolver.
*
* @return the request resolver
*/
protected OAuth2AuthorizationRequestResolver requestResolver() {
return new AadOAuth2AuthorizationRequestResolver(this.repo, properties);
}
} |
This is very nitpicky, but I wonder if this should just say `"none"`. Given the format of the string we'd end up with something like: ``` [Authenticated account] Client ID: No Application Identifier Available, Tenant ID:... ``` Which both feels wordy and also because the consts don't match the string you get weird disconnects. | private String getAccountIdentifierMessage(String identifierName, String identifierValue) {
if (identifierValue == null) {
return "No " + identifierName + " available.";
}
return identifierValue;
} | return "No " + identifierName + " available."; | private String getAccountIdentifierMessage(String identifierName, String identifierValue) {
if (identifierValue == null) {
return "No " + identifierName + " available.";
}
return identifierValue;
} | class HttpPipelineAdapter implements IHttpClient {
private static final ClientLogger CLIENT_LOGGER = new ClientLogger(HttpPipelineAdapter.class);
private static final JsonFactory JSON_FACTORY = new JsonFactory();
private static final String ACCOUNT_IDENTIFIER_LOG_MESSAGE = "[Authenticated account] Client ID: {0}, Tenant ID: {1}"
+ ", User Principal Name: {2}, Object ID (user): {3})";
private static final String APPLICATION_IDENTIFIER = "Application Identifier";
private static final String OBJECT_ID = "Object Id";
private static final String TENANT_ID = "Tenant Id";
private static final String USER_PRINCIPAL_NAME = "User Principal Name";
private static final String ACCESS_TOKEN_JSON_KEY = "access_token";
private static final String APPLICATION_ID_JSON_KEY = "appid";
private static final String OBJECT_ID_JSON_KEY = "oid";
private static final String TENANT_ID_JSON_KEY = "tid";
private static final String USER_PRINCIPAL_NAME_JSON_KEY = "upn";
private final HttpPipeline httpPipeline;
private IdentityClientOptions identityClientOptions;
HttpPipelineAdapter(HttpPipeline httpPipeline, IdentityClientOptions identityClientOptions) {
this.httpPipeline = httpPipeline;
this.identityClientOptions = identityClientOptions;
}
@Override
public IHttpResponse send(HttpRequest httpRequest) {
com.azure.core.http.HttpRequest request = new com.azure.core.http.HttpRequest(
HttpMethod.valueOf(httpRequest.httpMethod().name()),
httpRequest.url());
if (httpRequest.headers() != null) {
request.setHeaders(new HttpHeaders(httpRequest.headers()));
}
if (httpRequest.body() != null) {
request.setBody(httpRequest.body());
}
return httpPipeline.send(request)
.flatMap(response -> response.getBodyAsString()
.map(body -> {
logAccounIdentifiersIfConfigured(body);
com.microsoft.aad.msal4j.HttpResponse httpResponse = new com.microsoft.aad.msal4j.HttpResponse()
.body(body)
.statusCode(response.getStatusCode());
httpResponse.addHeaders(response.getHeaders().stream().collect(Collectors.toMap(HttpHeader::getName,
HttpHeader::getValuesList)));
return httpResponse;
})
.switchIfEmpty(Mono.defer(() -> {
com.microsoft.aad.msal4j.HttpResponse httpResponse = new com.microsoft.aad.msal4j.HttpResponse()
.statusCode(response.getStatusCode());
httpResponse.addHeaders(response.getHeaders().stream().collect(Collectors.toMap(HttpHeader::getName,
HttpHeader::getValuesList)));
return Mono.just(httpResponse);
})))
.block();
}
private void logAccounIdentifiersIfConfigured(String body) {
if (identityClientOptions != null
&& !identityClientOptions.getIdentityLogOptionsImpl().isLoggingAccountIdentifiersAllowed()) {
return;
}
try {
JsonParser responseParser = JSON_FACTORY.createParser(body);
String accessToken = getTargetFieldValueFromJsonParser(responseParser, ACCESS_TOKEN_JSON_KEY);
responseParser.close();
if (accessToken != null) {
String[] base64Metadata = accessToken.split("\\.");
if (base64Metadata.length > 1) {
byte[] decoded = Base64.getDecoder().decode(base64Metadata[1]);
String data = new String(decoded, StandardCharsets.UTF_8);
JsonParser jsonParser = JSON_FACTORY.createParser(data);
HashMap<String, String> jsonMap = parseJsonIntoMap(jsonParser);
jsonParser.close();
String appId = jsonMap.containsKey(APPLICATION_ID_JSON_KEY)
? jsonMap.get(APPLICATION_ID_JSON_KEY) : null;
String objectId = jsonMap.containsKey(OBJECT_ID_JSON_KEY)
? jsonMap.get(OBJECT_ID_JSON_KEY) : null;
String tenantId = jsonMap.containsKey(TENANT_ID_JSON_KEY)
? jsonMap.get(TENANT_ID_JSON_KEY) : null;
String userPrincipalName = jsonMap.containsKey(USER_PRINCIPAL_NAME_JSON_KEY)
? jsonMap.get(USER_PRINCIPAL_NAME_JSON_KEY) : null;
CLIENT_LOGGER.log(LogLevel.INFORMATIONAL, () -> MessageFormat
.format(ACCOUNT_IDENTIFIER_LOG_MESSAGE,
getAccountIdentifierMessage(APPLICATION_IDENTIFIER, appId),
getAccountIdentifierMessage(OBJECT_ID, objectId),
getAccountIdentifierMessage(TENANT_ID, tenantId),
getAccountIdentifierMessage(USER_PRINCIPAL_NAME,
userPrincipalName)));
}
}
} catch (IOException e) {
CLIENT_LOGGER.log(LogLevel.WARNING, () -> "allowLoggingAccountIdentifiers Log option was set,"
+ " but the account information could not be logged.", e);
}
}
private String getTargetFieldValueFromJsonParser(JsonParser jsonParser, String targetField) throws IOException {
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jsonParser.getCurrentName();
if (targetField.equals(fieldName)) {
jsonParser.nextToken();
return jsonParser.getText();
}
}
return null;
}
private HashMap<String, String> parseJsonIntoMap(JsonParser jsonParser) throws IOException {
HashMap<String, String> output = new HashMap<>();
JsonToken currentToken = jsonParser.nextToken();
if (jsonParser.getCurrentName() == null) {
currentToken = jsonParser.nextToken();
}
while (currentToken != JsonToken.END_OBJECT) {
String fieldName = jsonParser.getCurrentName();
jsonParser.nextToken();
String value = jsonParser.getText();
output.put(fieldName, value);
currentToken = jsonParser.nextToken();
}
return output;
}
} | class HttpPipelineAdapter implements IHttpClient {
private static final ClientLogger CLIENT_LOGGER = new ClientLogger(HttpPipelineAdapter.class);
private static final JsonFactory JSON_FACTORY = new JsonFactory();
private static final String ACCOUNT_IDENTIFIER_LOG_MESSAGE = "[Authenticated account] Client ID: {0}, Tenant ID: {1}"
+ ", User Principal Name: {2}, Object ID (user): {3})";
private static final String APPLICATION_IDENTIFIER = "Application Identifier";
private static final String OBJECT_ID = "Object Id";
private static final String TENANT_ID = "Tenant Id";
private static final String USER_PRINCIPAL_NAME = "User Principal Name";
private static final String ACCESS_TOKEN_JSON_KEY = "access_token";
private static final String APPLICATION_ID_JSON_KEY = "appid";
private static final String OBJECT_ID_JSON_KEY = "oid";
private static final String TENANT_ID_JSON_KEY = "tid";
private static final String USER_PRINCIPAL_NAME_JSON_KEY = "upn";
private final HttpPipeline httpPipeline;
private IdentityClientOptions identityClientOptions;
HttpPipelineAdapter(HttpPipeline httpPipeline, IdentityClientOptions identityClientOptions) {
this.httpPipeline = httpPipeline;
this.identityClientOptions = identityClientOptions;
}
@Override
public IHttpResponse send(HttpRequest httpRequest) {
com.azure.core.http.HttpRequest request = new com.azure.core.http.HttpRequest(
HttpMethod.valueOf(httpRequest.httpMethod().name()),
httpRequest.url());
if (httpRequest.headers() != null) {
request.setHeaders(new HttpHeaders(httpRequest.headers()));
}
if (httpRequest.body() != null) {
request.setBody(httpRequest.body());
}
return httpPipeline.send(request)
.flatMap(response -> response.getBodyAsString()
.map(body -> {
logAccountIdentifiersIfConfigured(body);
com.microsoft.aad.msal4j.HttpResponse httpResponse = new com.microsoft.aad.msal4j.HttpResponse()
.body(body)
.statusCode(response.getStatusCode());
httpResponse.addHeaders(response.getHeaders().stream().collect(Collectors.toMap(HttpHeader::getName,
HttpHeader::getValuesList)));
return httpResponse;
})
.switchIfEmpty(Mono.defer(() -> {
com.microsoft.aad.msal4j.HttpResponse httpResponse = new com.microsoft.aad.msal4j.HttpResponse()
.statusCode(response.getStatusCode());
httpResponse.addHeaders(response.getHeaders().stream().collect(Collectors.toMap(HttpHeader::getName,
HttpHeader::getValuesList)));
return Mono.just(httpResponse);
})))
.block();
}
private void logAccountIdentifiersIfConfigured(String body) {
if (identityClientOptions == null
|| !identityClientOptions.getIdentityLogOptionsImpl().isLoggingAccountIdentifiersAllowed()) {
return;
}
try {
JsonParser responseParser = JSON_FACTORY.createParser(body);
String accessToken = getTargetFieldValueFromJsonParser(responseParser, ACCESS_TOKEN_JSON_KEY);
responseParser.close();
if (accessToken != null) {
String[] base64Metadata = accessToken.split("\\.");
if (base64Metadata.length > 1) {
byte[] decoded = Base64.getDecoder().decode(base64Metadata[1]);
String data = new String(decoded, StandardCharsets.UTF_8);
JsonParser jsonParser = JSON_FACTORY.createParser(data);
HashMap<String, String> jsonMap = parseJsonIntoMap(jsonParser);
jsonParser.close();
String appId = jsonMap.containsKey(APPLICATION_ID_JSON_KEY)
? jsonMap.get(APPLICATION_ID_JSON_KEY) : null;
String objectId = jsonMap.containsKey(OBJECT_ID_JSON_KEY)
? jsonMap.get(OBJECT_ID_JSON_KEY) : null;
String tenantId = jsonMap.containsKey(TENANT_ID_JSON_KEY)
? jsonMap.get(TENANT_ID_JSON_KEY) : null;
String userPrincipalName = jsonMap.containsKey(USER_PRINCIPAL_NAME_JSON_KEY)
? jsonMap.get(USER_PRINCIPAL_NAME_JSON_KEY) : null;
CLIENT_LOGGER.log(LogLevel.INFORMATIONAL, () -> MessageFormat
.format(ACCOUNT_IDENTIFIER_LOG_MESSAGE,
getAccountIdentifierMessage(APPLICATION_IDENTIFIER, appId),
getAccountIdentifierMessage(TENANT_ID, tenantId),
getAccountIdentifierMessage(USER_PRINCIPAL_NAME, userPrincipalName),
getAccountIdentifierMessage(OBJECT_ID, objectId)));
}
}
} catch (IOException e) {
CLIENT_LOGGER.log(LogLevel.WARNING, () -> "allowLoggingAccountIdentifiers Log option was set,"
+ " but the account information could not be logged.", e);
}
}
private String getTargetFieldValueFromJsonParser(JsonParser jsonParser, String targetField) throws IOException {
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jsonParser.getCurrentName();
if (targetField.equals(fieldName)) {
jsonParser.nextToken();
return jsonParser.getText();
}
}
return null;
}
private HashMap<String, String> parseJsonIntoMap(JsonParser jsonParser) throws IOException {
HashMap<String, String> output = new HashMap<>();
JsonToken currentToken = jsonParser.nextToken();
if (jsonParser.getCurrentName() == null) {
currentToken = jsonParser.nextToken();
}
while (currentToken != JsonToken.END_OBJECT) {
String fieldName = jsonParser.getCurrentName();
jsonParser.nextToken();
String value = jsonParser.getText();
output.put(fieldName, value);
currentToken = jsonParser.nextToken();
}
return output;
}
} |
This we need to align with other languages too then. For beta we keep as it is, on next meeting we can discuss this to see what other languages align with. | private String getAccountIdentifierMessage(String identifierName, String identifierValue) {
if (identifierValue == null) {
return "No " + identifierName + " available.";
}
return identifierValue;
} | return "No " + identifierName + " available."; | private String getAccountIdentifierMessage(String identifierName, String identifierValue) {
if (identifierValue == null) {
return "No " + identifierName + " available.";
}
return identifierValue;
} | class HttpPipelineAdapter implements IHttpClient {
private static final ClientLogger CLIENT_LOGGER = new ClientLogger(HttpPipelineAdapter.class);
private static final JsonFactory JSON_FACTORY = new JsonFactory();
private static final String ACCOUNT_IDENTIFIER_LOG_MESSAGE = "[Authenticated account] Client ID: {0}, Tenant ID: {1}"
+ ", User Principal Name: {2}, Object ID (user): {3})";
private static final String APPLICATION_IDENTIFIER = "Application Identifier";
private static final String OBJECT_ID = "Object Id";
private static final String TENANT_ID = "Tenant Id";
private static final String USER_PRINCIPAL_NAME = "User Principal Name";
private static final String ACCESS_TOKEN_JSON_KEY = "access_token";
private static final String APPLICATION_ID_JSON_KEY = "appid";
private static final String OBJECT_ID_JSON_KEY = "oid";
private static final String TENANT_ID_JSON_KEY = "tid";
private static final String USER_PRINCIPAL_NAME_JSON_KEY = "upn";
private final HttpPipeline httpPipeline;
private IdentityClientOptions identityClientOptions;
HttpPipelineAdapter(HttpPipeline httpPipeline, IdentityClientOptions identityClientOptions) {
this.httpPipeline = httpPipeline;
this.identityClientOptions = identityClientOptions;
}
@Override
public IHttpResponse send(HttpRequest httpRequest) {
com.azure.core.http.HttpRequest request = new com.azure.core.http.HttpRequest(
HttpMethod.valueOf(httpRequest.httpMethod().name()),
httpRequest.url());
if (httpRequest.headers() != null) {
request.setHeaders(new HttpHeaders(httpRequest.headers()));
}
if (httpRequest.body() != null) {
request.setBody(httpRequest.body());
}
return httpPipeline.send(request)
.flatMap(response -> response.getBodyAsString()
.map(body -> {
logAccounIdentifiersIfConfigured(body);
com.microsoft.aad.msal4j.HttpResponse httpResponse = new com.microsoft.aad.msal4j.HttpResponse()
.body(body)
.statusCode(response.getStatusCode());
httpResponse.addHeaders(response.getHeaders().stream().collect(Collectors.toMap(HttpHeader::getName,
HttpHeader::getValuesList)));
return httpResponse;
})
.switchIfEmpty(Mono.defer(() -> {
com.microsoft.aad.msal4j.HttpResponse httpResponse = new com.microsoft.aad.msal4j.HttpResponse()
.statusCode(response.getStatusCode());
httpResponse.addHeaders(response.getHeaders().stream().collect(Collectors.toMap(HttpHeader::getName,
HttpHeader::getValuesList)));
return Mono.just(httpResponse);
})))
.block();
}
private void logAccounIdentifiersIfConfigured(String body) {
if (identityClientOptions != null
&& !identityClientOptions.getIdentityLogOptionsImpl().isLoggingAccountIdentifiersAllowed()) {
return;
}
try {
JsonParser responseParser = JSON_FACTORY.createParser(body);
String accessToken = getTargetFieldValueFromJsonParser(responseParser, ACCESS_TOKEN_JSON_KEY);
responseParser.close();
if (accessToken != null) {
String[] base64Metadata = accessToken.split("\\.");
if (base64Metadata.length > 1) {
byte[] decoded = Base64.getDecoder().decode(base64Metadata[1]);
String data = new String(decoded, StandardCharsets.UTF_8);
JsonParser jsonParser = JSON_FACTORY.createParser(data);
HashMap<String, String> jsonMap = parseJsonIntoMap(jsonParser);
jsonParser.close();
String appId = jsonMap.containsKey(APPLICATION_ID_JSON_KEY)
? jsonMap.get(APPLICATION_ID_JSON_KEY) : null;
String objectId = jsonMap.containsKey(OBJECT_ID_JSON_KEY)
? jsonMap.get(OBJECT_ID_JSON_KEY) : null;
String tenantId = jsonMap.containsKey(TENANT_ID_JSON_KEY)
? jsonMap.get(TENANT_ID_JSON_KEY) : null;
String userPrincipalName = jsonMap.containsKey(USER_PRINCIPAL_NAME_JSON_KEY)
? jsonMap.get(USER_PRINCIPAL_NAME_JSON_KEY) : null;
CLIENT_LOGGER.log(LogLevel.INFORMATIONAL, () -> MessageFormat
.format(ACCOUNT_IDENTIFIER_LOG_MESSAGE,
getAccountIdentifierMessage(APPLICATION_IDENTIFIER, appId),
getAccountIdentifierMessage(OBJECT_ID, objectId),
getAccountIdentifierMessage(TENANT_ID, tenantId),
getAccountIdentifierMessage(USER_PRINCIPAL_NAME,
userPrincipalName)));
}
}
} catch (IOException e) {
CLIENT_LOGGER.log(LogLevel.WARNING, () -> "allowLoggingAccountIdentifiers Log option was set,"
+ " but the account information could not be logged.", e);
}
}
private String getTargetFieldValueFromJsonParser(JsonParser jsonParser, String targetField) throws IOException {
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jsonParser.getCurrentName();
if (targetField.equals(fieldName)) {
jsonParser.nextToken();
return jsonParser.getText();
}
}
return null;
}
private HashMap<String, String> parseJsonIntoMap(JsonParser jsonParser) throws IOException {
HashMap<String, String> output = new HashMap<>();
JsonToken currentToken = jsonParser.nextToken();
if (jsonParser.getCurrentName() == null) {
currentToken = jsonParser.nextToken();
}
while (currentToken != JsonToken.END_OBJECT) {
String fieldName = jsonParser.getCurrentName();
jsonParser.nextToken();
String value = jsonParser.getText();
output.put(fieldName, value);
currentToken = jsonParser.nextToken();
}
return output;
}
} | class HttpPipelineAdapter implements IHttpClient {
private static final ClientLogger CLIENT_LOGGER = new ClientLogger(HttpPipelineAdapter.class);
private static final JsonFactory JSON_FACTORY = new JsonFactory();
private static final String ACCOUNT_IDENTIFIER_LOG_MESSAGE = "[Authenticated account] Client ID: {0}, Tenant ID: {1}"
+ ", User Principal Name: {2}, Object ID (user): {3})";
private static final String APPLICATION_IDENTIFIER = "Application Identifier";
private static final String OBJECT_ID = "Object Id";
private static final String TENANT_ID = "Tenant Id";
private static final String USER_PRINCIPAL_NAME = "User Principal Name";
private static final String ACCESS_TOKEN_JSON_KEY = "access_token";
private static final String APPLICATION_ID_JSON_KEY = "appid";
private static final String OBJECT_ID_JSON_KEY = "oid";
private static final String TENANT_ID_JSON_KEY = "tid";
private static final String USER_PRINCIPAL_NAME_JSON_KEY = "upn";
private final HttpPipeline httpPipeline;
private IdentityClientOptions identityClientOptions;
HttpPipelineAdapter(HttpPipeline httpPipeline, IdentityClientOptions identityClientOptions) {
this.httpPipeline = httpPipeline;
this.identityClientOptions = identityClientOptions;
}
@Override
public IHttpResponse send(HttpRequest httpRequest) {
com.azure.core.http.HttpRequest request = new com.azure.core.http.HttpRequest(
HttpMethod.valueOf(httpRequest.httpMethod().name()),
httpRequest.url());
if (httpRequest.headers() != null) {
request.setHeaders(new HttpHeaders(httpRequest.headers()));
}
if (httpRequest.body() != null) {
request.setBody(httpRequest.body());
}
return httpPipeline.send(request)
.flatMap(response -> response.getBodyAsString()
.map(body -> {
logAccountIdentifiersIfConfigured(body);
com.microsoft.aad.msal4j.HttpResponse httpResponse = new com.microsoft.aad.msal4j.HttpResponse()
.body(body)
.statusCode(response.getStatusCode());
httpResponse.addHeaders(response.getHeaders().stream().collect(Collectors.toMap(HttpHeader::getName,
HttpHeader::getValuesList)));
return httpResponse;
})
.switchIfEmpty(Mono.defer(() -> {
com.microsoft.aad.msal4j.HttpResponse httpResponse = new com.microsoft.aad.msal4j.HttpResponse()
.statusCode(response.getStatusCode());
httpResponse.addHeaders(response.getHeaders().stream().collect(Collectors.toMap(HttpHeader::getName,
HttpHeader::getValuesList)));
return Mono.just(httpResponse);
})))
.block();
}
private void logAccountIdentifiersIfConfigured(String body) {
if (identityClientOptions == null
|| !identityClientOptions.getIdentityLogOptionsImpl().isLoggingAccountIdentifiersAllowed()) {
return;
}
try {
JsonParser responseParser = JSON_FACTORY.createParser(body);
String accessToken = getTargetFieldValueFromJsonParser(responseParser, ACCESS_TOKEN_JSON_KEY);
responseParser.close();
if (accessToken != null) {
String[] base64Metadata = accessToken.split("\\.");
if (base64Metadata.length > 1) {
byte[] decoded = Base64.getDecoder().decode(base64Metadata[1]);
String data = new String(decoded, StandardCharsets.UTF_8);
JsonParser jsonParser = JSON_FACTORY.createParser(data);
HashMap<String, String> jsonMap = parseJsonIntoMap(jsonParser);
jsonParser.close();
String appId = jsonMap.containsKey(APPLICATION_ID_JSON_KEY)
? jsonMap.get(APPLICATION_ID_JSON_KEY) : null;
String objectId = jsonMap.containsKey(OBJECT_ID_JSON_KEY)
? jsonMap.get(OBJECT_ID_JSON_KEY) : null;
String tenantId = jsonMap.containsKey(TENANT_ID_JSON_KEY)
? jsonMap.get(TENANT_ID_JSON_KEY) : null;
String userPrincipalName = jsonMap.containsKey(USER_PRINCIPAL_NAME_JSON_KEY)
? jsonMap.get(USER_PRINCIPAL_NAME_JSON_KEY) : null;
CLIENT_LOGGER.log(LogLevel.INFORMATIONAL, () -> MessageFormat
.format(ACCOUNT_IDENTIFIER_LOG_MESSAGE,
getAccountIdentifierMessage(APPLICATION_IDENTIFIER, appId),
getAccountIdentifierMessage(TENANT_ID, tenantId),
getAccountIdentifierMessage(USER_PRINCIPAL_NAME, userPrincipalName),
getAccountIdentifierMessage(OBJECT_ID, objectId)));
}
}
} catch (IOException e) {
CLIENT_LOGGER.log(LogLevel.WARNING, () -> "allowLoggingAccountIdentifiers Log option was set,"
+ " but the account information could not be logged.", e);
}
}
private String getTargetFieldValueFromJsonParser(JsonParser jsonParser, String targetField) throws IOException {
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jsonParser.getCurrentName();
if (targetField.equals(fieldName)) {
jsonParser.nextToken();
return jsonParser.getText();
}
}
return null;
}
private HashMap<String, String> parseJsonIntoMap(JsonParser jsonParser) throws IOException {
HashMap<String, String> output = new HashMap<>();
JsonToken currentToken = jsonParser.nextToken();
if (jsonParser.getCurrentName() == null) {
currentToken = jsonParser.nextToken();
}
while (currentToken != JsonToken.END_OBJECT) {
String fieldName = jsonParser.getCurrentName();
jsonParser.nextToken();
String value = jsonParser.getText();
output.put(fieldName, value);
currentToken = jsonParser.nextToken();
}
return output;
}
} |
Could look into generalizing the Flux backed InputStream implementation that one of the Storage libraries use | private static RequestBody toOkHttpRequestBodySynchronously(BinaryData bodyContent, HttpHeaders headers) {
String contentType = headers.getValue("Content-Type");
MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType);
if (bodyContent == null) {
return RequestBody.create(ByteString.EMPTY, mediaType);
}
BinaryDataContent content = BinaryDataHelper.getContent(bodyContent);
if (content instanceof ByteArrayContent) {
return RequestBody.create(content.toBytes(), mediaType);
} else if (content instanceof FileContent) {
FileContent fileContent = (FileContent) content;
return RequestBody.create(fileContent.getFile().toFile(), mediaType);
} else if (content instanceof StringContent) {
return RequestBody.create(bodyContent.toString(), mediaType);
} else if (content instanceof InputStreamContent) {
return RequestBody.create(toByteString(content.toStream()), mediaType);
} else {
return toByteString(bodyContent.toFluxByteBuffer()).map(bs -> RequestBody.create(bs, mediaType)).block();
}
} | private static RequestBody toOkHttpRequestBodySynchronously(BinaryData bodyContent, HttpHeaders headers) {
String contentType = headers.getValue("Content-Type");
MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType);
if (bodyContent == null) {
return RequestBody.create(ByteString.EMPTY, mediaType);
}
BinaryDataContent content = BinaryDataHelper.getContent(bodyContent);
if (content instanceof ByteArrayContent) {
return RequestBody.create(content.toBytes(), mediaType);
} else if (content instanceof FileContent) {
FileContent fileContent = (FileContent) content;
return RequestBody.create(fileContent.getFile().toFile(), mediaType);
} else if (content instanceof StringContent) {
return RequestBody.create(bodyContent.toString(), mediaType);
} else if (content instanceof InputStreamContent) {
return RequestBody.create(toByteString(content.toStream()), mediaType);
} else {
return toByteString(bodyContent.toFluxByteBuffer()).map(bs -> RequestBody.create(bs, mediaType)).block();
}
} | class OkHttpAsyncHttpClient implements HttpClient {
private static final ClientLogger LOGGER = new ClientLogger(OkHttpAsyncHttpClient.class);
final OkHttpClient httpClient;
private static final Mono<okio.ByteString> EMPTY_BYTE_STRING_MONO = Mono.just(okio.ByteString.EMPTY);
OkHttpAsyncHttpClient(OkHttpClient httpClient) {
this.httpClient = httpClient;
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Context.NONE);
}
@Override
public Mono<HttpResponse> send(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
return Mono.create(sink -> sink.onRequest(value -> {
toOkHttpRequest(request).subscribe(okHttpRequest -> {
try {
Call call = httpClient.newCall(okHttpRequest);
call.enqueue(new OkHttpCallback(sink, request, eagerlyReadResponse));
sink.onCancel(call::cancel);
} catch (Exception ex) {
sink.error(ex);
}
}, sink::error);
}));
}
@Override
public HttpResponse sendSynchronously(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
Request okHttpRequest = toOkHttpRequestSynchronously(request);
Call call = httpClient.newCall(okHttpRequest);
try {
Response okHttpResponse = call.execute();
return fromOkHttpResponse(okHttpResponse, request, eagerlyReadResponse);
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(e));
}
}
/**
* Converts the given azure-core request to okhttp request.
*
* @param request the azure-core request
* @return the Mono emitting okhttp request
*/
private static Mono<okhttp3.Request> toOkHttpRequest(HttpRequest request) {
Request.Builder requestBuilder = new Request.Builder()
.url(request.getUrl());
if (request.getHeaders() != null) {
for (HttpHeader hdr : request.getHeaders()) {
hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value));
}
}
if (request.getHttpMethod() == HttpMethod.GET) {
return Mono.just(requestBuilder.get().build());
} else if (request.getHttpMethod() == HttpMethod.HEAD) {
return Mono.just(requestBuilder.head().build());
}
return toOkHttpRequestBody(request.getContent(), request.getHeaders())
.map(okhttpRequestBody -> requestBuilder.method(request.getHttpMethod().toString(), okhttpRequestBody)
.build());
}
/**
* Converts the given azure-core request to okhttp request.
*
* @param request the azure-core request
* @return the Mono emitting okhttp request
*/
private static okhttp3.Request toOkHttpRequestSynchronously(HttpRequest request) {
Request.Builder requestBuilder = new Request.Builder()
.url(request.getUrl());
if (request.getHeaders() != null) {
for (HttpHeader hdr : request.getHeaders()) {
hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value));
}
}
if (request.getHttpMethod() == HttpMethod.GET) {
return requestBuilder.get().build();
} else if (request.getHttpMethod() == HttpMethod.HEAD) {
return requestBuilder.head().build();
}
RequestBody requestBody = toOkHttpRequestBodySynchronously(request.getContent(), request.getHeaders());
return requestBuilder.method(request.getHttpMethod().toString(), requestBody)
.build();
}
/**
* Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux.
*
* @param bodyContent The BinaryData request body
* @param headers the headers associated with the original request
* @return the Mono emitting okhttp3.RequestBody
*/
/**
* Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux.
*
* @param bodyContent The BinaryData request body
* @param headers the headers associated with the original request
* @return the Mono emitting okhttp3.RequestBody
*/
private static Mono<RequestBody> toOkHttpRequestBody(BinaryData bodyContent, HttpHeaders headers) {
String contentType = headers.getValue("Content-Type");
MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType);
if (bodyContent == null) {
return Mono.defer(() -> Mono.just(RequestBody.create(ByteString.EMPTY, mediaType)));
}
BinaryDataContent content = BinaryDataHelper.getContent(bodyContent);
if (content instanceof ByteArrayContent) {
return Mono.defer(() -> Mono.just(RequestBody.create(content.toBytes(), mediaType)));
} else if (content instanceof FileContent) {
FileContent fileContent = (FileContent) content;
return Mono.defer(() -> Mono.just(RequestBody.create(fileContent.getFile().toFile(), mediaType)));
} else if (content instanceof StringContent) {
return Mono.defer(() -> Mono.just(RequestBody.create(bodyContent.toString(), mediaType)));
} else {
return toByteString(bodyContent.toFluxByteBuffer()).map(bs -> RequestBody.create(bs, mediaType));
}
}
/**
* Aggregate Flux of java.nio.ByteBuffer to single okio.ByteString.
*
* Pooled okio.Buffer type is used to buffer emitted ByteBuffer instances. Content of each ByteBuffer will be
* written (i.e copied) to the internal okio.Buffer slots. Once the stream terminates, the contents of all slots get
* copied to one single byte array and okio.ByteString will be created referring this byte array. Finally, the
* initial okio.Buffer will be returned to the pool.
*
* @param bbFlux the Flux of ByteBuffer to aggregate
* @return a mono emitting aggregated ByteString
*/
private static Mono<ByteString> toByteString(Flux<ByteBuffer> bbFlux) {
Objects.requireNonNull(bbFlux, "'bbFlux' cannot be null.");
return Mono.using(okio.Buffer::new,
buffer -> bbFlux.reduce(buffer, (b, byteBuffer) -> {
try {
b.write(byteBuffer);
return b;
} catch (IOException ioe) {
throw Exceptions.propagate(ioe);
}
}).map(b -> ByteString.of(b.readByteArray())), okio.Buffer::clear)
.switchIfEmpty(Mono.defer(() -> EMPTY_BYTE_STRING_MONO));
}
/**
* Aggregate InputStream to single okio.ByteString.
*
* @param inputStream the InputStream to aggregate
* @return Aggregated ByteString
*/
private static ByteString toByteString(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int nRead;
byte[] buffer = new byte[8192];
try (InputStream closeableInputStream = inputStream) {
while ((nRead = closeableInputStream.read(buffer, 0, buffer.length)) != -1) {
outputStream.write(buffer, 0, nRead);
}
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(e));
}
return ByteString.of(outputStream.toByteArray());
}
private static HttpResponse fromOkHttpResponse(
okhttp3.Response response, HttpRequest request, boolean eagerlyReadResponse) throws IOException {
/*
* Use a buffered response when we are eagerly reading the response from the network and the body isn't
* empty.
*/
if (eagerlyReadResponse) {
ResponseBody body = response.body();
if (Objects.nonNull(body)) {
byte[] bytes = body.bytes();
body.close();
return new OkHttpAsyncBufferedResponse(response, request, bytes);
} else {
return new OkHttpAsyncResponse(response, request);
}
} else {
return new OkHttpAsyncResponse(response, request);
}
}
private static class OkHttpCallback implements okhttp3.Callback {
private final MonoSink<HttpResponse> sink;
private final HttpRequest request;
private final boolean eagerlyReadResponse;
OkHttpCallback(MonoSink<HttpResponse> sink, HttpRequest request, boolean eagerlyReadResponse) {
this.sink = sink;
this.request = request;
this.eagerlyReadResponse = eagerlyReadResponse;
}
@SuppressWarnings("NullableProblems")
@Override
public void onFailure(okhttp3.Call call, IOException e) {
sink.error(e);
}
@SuppressWarnings("NullableProblems")
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) {
try {
HttpResponse httpResponse = fromOkHttpResponse(response, request, eagerlyReadResponse);
sink.success(httpResponse);
} catch (IOException ex) {
sink.error(ex);
}
}
}
} | class OkHttpAsyncHttpClient implements HttpClient {
private static final ClientLogger LOGGER = new ClientLogger(OkHttpAsyncHttpClient.class);
final OkHttpClient httpClient;
private static final Mono<okio.ByteString> EMPTY_BYTE_STRING_MONO = Mono.just(okio.ByteString.EMPTY);
OkHttpAsyncHttpClient(OkHttpClient httpClient) {
this.httpClient = httpClient;
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Context.NONE);
}
@Override
public Mono<HttpResponse> send(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
return Mono.create(sink -> sink.onRequest(value -> {
toOkHttpRequest(request).subscribe(okHttpRequest -> {
try {
Call call = httpClient.newCall(okHttpRequest);
call.enqueue(new OkHttpCallback(sink, request, eagerlyReadResponse));
sink.onCancel(call::cancel);
} catch (Exception ex) {
sink.error(ex);
}
}, sink::error);
}));
}
@Override
public HttpResponse sendSynchronously(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
Request okHttpRequest = toOkHttpRequestSynchronously(request);
Call call = httpClient.newCall(okHttpRequest);
try {
Response okHttpResponse = call.execute();
return fromOkHttpResponse(okHttpResponse, request, eagerlyReadResponse);
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(e));
}
}
/**
* Converts the given azure-core request to okhttp request.
*
* @param request the azure-core request
* @return the Mono emitting okhttp request
*/
private static Mono<okhttp3.Request> toOkHttpRequest(HttpRequest request) {
Request.Builder requestBuilder = new Request.Builder()
.url(request.getUrl());
if (request.getHeaders() != null) {
for (HttpHeader hdr : request.getHeaders()) {
hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value));
}
}
if (request.getHttpMethod() == HttpMethod.GET) {
return Mono.just(requestBuilder.get().build());
} else if (request.getHttpMethod() == HttpMethod.HEAD) {
return Mono.just(requestBuilder.head().build());
}
return toOkHttpRequestBody(request.getContent(), request.getHeaders())
.map(okhttpRequestBody -> requestBuilder.method(request.getHttpMethod().toString(), okhttpRequestBody)
.build());
}
/**
* Converts the given azure-core request to okhttp request.
*
* @param request the azure-core request
* @return the Mono emitting okhttp request
*/
private static okhttp3.Request toOkHttpRequestSynchronously(HttpRequest request) {
Request.Builder requestBuilder = new Request.Builder()
.url(request.getUrl());
if (request.getHeaders() != null) {
for (HttpHeader hdr : request.getHeaders()) {
hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value));
}
}
if (request.getHttpMethod() == HttpMethod.GET) {
return requestBuilder.get().build();
} else if (request.getHttpMethod() == HttpMethod.HEAD) {
return requestBuilder.head().build();
}
RequestBody requestBody = toOkHttpRequestBodySynchronously(request.getContent(), request.getHeaders());
return requestBuilder.method(request.getHttpMethod().toString(), requestBody)
.build();
}
/**
* Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux.
*
* @param bodyContent The BinaryData request body
* @param headers the headers associated with the original request
* @return the Mono emitting okhttp3.RequestBody
*/
/**
* Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux.
*
* @param bodyContent The BinaryData request body
* @param headers the headers associated with the original request
* @return the Mono emitting okhttp3.RequestBody
*/
private static Mono<RequestBody> toOkHttpRequestBody(BinaryData bodyContent, HttpHeaders headers) {
String contentType = headers.getValue("Content-Type");
MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType);
if (bodyContent == null) {
return Mono.defer(() -> Mono.just(RequestBody.create(ByteString.EMPTY, mediaType)));
}
BinaryDataContent content = BinaryDataHelper.getContent(bodyContent);
if (content instanceof ByteArrayContent) {
return Mono.defer(() -> Mono.just(RequestBody.create(content.toBytes(), mediaType)));
} else if (content instanceof FileContent) {
FileContent fileContent = (FileContent) content;
return Mono.defer(() -> Mono.just(RequestBody.create(fileContent.getFile().toFile(), mediaType)));
} else if (content instanceof StringContent) {
return Mono.defer(() -> Mono.just(RequestBody.create(bodyContent.toString(), mediaType)));
} else {
return toByteString(bodyContent.toFluxByteBuffer()).map(bs -> RequestBody.create(bs, mediaType));
}
}
/**
* Aggregate Flux of java.nio.ByteBuffer to single okio.ByteString.
*
* Pooled okio.Buffer type is used to buffer emitted ByteBuffer instances. Content of each ByteBuffer will be
* written (i.e copied) to the internal okio.Buffer slots. Once the stream terminates, the contents of all slots get
* copied to one single byte array and okio.ByteString will be created referring this byte array. Finally, the
* initial okio.Buffer will be returned to the pool.
*
* @param bbFlux the Flux of ByteBuffer to aggregate
* @return a mono emitting aggregated ByteString
*/
private static Mono<ByteString> toByteString(Flux<ByteBuffer> bbFlux) {
Objects.requireNonNull(bbFlux, "'bbFlux' cannot be null.");
return Mono.using(okio.Buffer::new,
buffer -> bbFlux.reduce(buffer, (b, byteBuffer) -> {
try {
b.write(byteBuffer);
return b;
} catch (IOException ioe) {
throw Exceptions.propagate(ioe);
}
}).map(b -> ByteString.of(b.readByteArray())), okio.Buffer::clear)
.switchIfEmpty(Mono.defer(() -> EMPTY_BYTE_STRING_MONO));
}
/**
* Aggregate InputStream to single okio.ByteString.
*
* @param inputStream the InputStream to aggregate
* @return Aggregated ByteString
*/
private static ByteString toByteString(InputStream inputStream) {
try (InputStream closeableInputStream = inputStream) {
byte[] content = StreamUtils.INSTANCE.readAllBytes(closeableInputStream);
return ByteString.of(content);
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(e));
}
}
private static HttpResponse fromOkHttpResponse(
okhttp3.Response response, HttpRequest request, boolean eagerlyReadResponse) throws IOException {
/*
* Use a buffered response when we are eagerly reading the response from the network and the body isn't
* empty.
*/
if (eagerlyReadResponse) {
ResponseBody body = response.body();
if (Objects.nonNull(body)) {
byte[] bytes = body.bytes();
body.close();
return new OkHttpAsyncBufferedResponse(response, request, bytes);
} else {
return new OkHttpAsyncResponse(response, request);
}
} else {
return new OkHttpAsyncResponse(response, request);
}
}
private static class OkHttpCallback implements okhttp3.Callback {
private final MonoSink<HttpResponse> sink;
private final HttpRequest request;
private final boolean eagerlyReadResponse;
OkHttpCallback(MonoSink<HttpResponse> sink, HttpRequest request, boolean eagerlyReadResponse) {
this.sink = sink;
this.request = request;
this.eagerlyReadResponse = eagerlyReadResponse;
}
@SuppressWarnings("NullableProblems")
@Override
public void onFailure(okhttp3.Call call, IOException e) {
sink.error(e);
}
@SuppressWarnings("NullableProblems")
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) {
try {
HttpResponse httpResponse = fromOkHttpResponse(response, request, eagerlyReadResponse);
sink.success(httpResponse);
} catch (IOException ex) {
sink.error(ex);
}
}
}
} | |
We should look at creating a utility method in Core that can optimize InputStream to byte[] conversion based on the type of InputStream | private static ByteString toByteString(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int nRead;
byte[] buffer = new byte[8192];
try (InputStream closeableInputStream = inputStream) {
while ((nRead = closeableInputStream.read(buffer, 0, buffer.length)) != -1) {
outputStream.write(buffer, 0, nRead);
}
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(e));
}
return ByteString.of(outputStream.toByteArray());
} | try (InputStream closeableInputStream = inputStream) { | private static ByteString toByteString(InputStream inputStream) {
try (InputStream closeableInputStream = inputStream) {
byte[] content = StreamUtils.INSTANCE.readAllBytes(closeableInputStream);
return ByteString.of(content);
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(e));
}
} | class OkHttpAsyncHttpClient implements HttpClient {
private static final ClientLogger LOGGER = new ClientLogger(OkHttpAsyncHttpClient.class);
final OkHttpClient httpClient;
private static final Mono<okio.ByteString> EMPTY_BYTE_STRING_MONO = Mono.just(okio.ByteString.EMPTY);
OkHttpAsyncHttpClient(OkHttpClient httpClient) {
this.httpClient = httpClient;
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Context.NONE);
}
@Override
public Mono<HttpResponse> send(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
return Mono.create(sink -> sink.onRequest(value -> {
toOkHttpRequest(request).subscribe(okHttpRequest -> {
try {
Call call = httpClient.newCall(okHttpRequest);
call.enqueue(new OkHttpCallback(sink, request, eagerlyReadResponse));
sink.onCancel(call::cancel);
} catch (Exception ex) {
sink.error(ex);
}
}, sink::error);
}));
}
@Override
public HttpResponse sendSynchronously(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
Request okHttpRequest = toOkHttpRequestSynchronously(request);
Call call = httpClient.newCall(okHttpRequest);
try {
Response okHttpResponse = call.execute();
return fromOkHttpResponse(okHttpResponse, request, eagerlyReadResponse);
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(e));
}
}
/**
* Converts the given azure-core request to okhttp request.
*
* @param request the azure-core request
* @return the Mono emitting okhttp request
*/
private static Mono<okhttp3.Request> toOkHttpRequest(HttpRequest request) {
Request.Builder requestBuilder = new Request.Builder()
.url(request.getUrl());
if (request.getHeaders() != null) {
for (HttpHeader hdr : request.getHeaders()) {
hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value));
}
}
if (request.getHttpMethod() == HttpMethod.GET) {
return Mono.just(requestBuilder.get().build());
} else if (request.getHttpMethod() == HttpMethod.HEAD) {
return Mono.just(requestBuilder.head().build());
}
return toOkHttpRequestBody(request.getContent(), request.getHeaders())
.map(okhttpRequestBody -> requestBuilder.method(request.getHttpMethod().toString(), okhttpRequestBody)
.build());
}
/**
* Converts the given azure-core request to okhttp request.
*
* @param request the azure-core request
* @return the Mono emitting okhttp request
*/
private static okhttp3.Request toOkHttpRequestSynchronously(HttpRequest request) {
Request.Builder requestBuilder = new Request.Builder()
.url(request.getUrl());
if (request.getHeaders() != null) {
for (HttpHeader hdr : request.getHeaders()) {
hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value));
}
}
if (request.getHttpMethod() == HttpMethod.GET) {
return requestBuilder.get().build();
} else if (request.getHttpMethod() == HttpMethod.HEAD) {
return requestBuilder.head().build();
}
RequestBody requestBody = toOkHttpRequestBodySynchronously(request.getContent(), request.getHeaders());
return requestBuilder.method(request.getHttpMethod().toString(), requestBody)
.build();
}
/**
* Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux.
*
* @param bodyContent The BinaryData request body
* @param headers the headers associated with the original request
* @return the Mono emitting okhttp3.RequestBody
*/
private static RequestBody toOkHttpRequestBodySynchronously(BinaryData bodyContent, HttpHeaders headers) {
String contentType = headers.getValue("Content-Type");
MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType);
if (bodyContent == null) {
return RequestBody.create(ByteString.EMPTY, mediaType);
}
BinaryDataContent content = BinaryDataHelper.getContent(bodyContent);
if (content instanceof ByteArrayContent) {
return RequestBody.create(content.toBytes(), mediaType);
} else if (content instanceof FileContent) {
FileContent fileContent = (FileContent) content;
return RequestBody.create(fileContent.getFile().toFile(), mediaType);
} else if (content instanceof StringContent) {
return RequestBody.create(bodyContent.toString(), mediaType);
} else if (content instanceof InputStreamContent) {
return RequestBody.create(toByteString(content.toStream()), mediaType);
} else {
return toByteString(bodyContent.toFluxByteBuffer()).map(bs -> RequestBody.create(bs, mediaType)).block();
}
}
/**
* Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux.
*
* @param bodyContent The BinaryData request body
* @param headers the headers associated with the original request
* @return the Mono emitting okhttp3.RequestBody
*/
private static Mono<RequestBody> toOkHttpRequestBody(BinaryData bodyContent, HttpHeaders headers) {
String contentType = headers.getValue("Content-Type");
MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType);
if (bodyContent == null) {
return Mono.defer(() -> Mono.just(RequestBody.create(ByteString.EMPTY, mediaType)));
}
BinaryDataContent content = BinaryDataHelper.getContent(bodyContent);
if (content instanceof ByteArrayContent) {
return Mono.defer(() -> Mono.just(RequestBody.create(content.toBytes(), mediaType)));
} else if (content instanceof FileContent) {
FileContent fileContent = (FileContent) content;
return Mono.defer(() -> Mono.just(RequestBody.create(fileContent.getFile().toFile(), mediaType)));
} else if (content instanceof StringContent) {
return Mono.defer(() -> Mono.just(RequestBody.create(bodyContent.toString(), mediaType)));
} else {
return toByteString(bodyContent.toFluxByteBuffer()).map(bs -> RequestBody.create(bs, mediaType));
}
}
/**
* Aggregate Flux of java.nio.ByteBuffer to single okio.ByteString.
*
* Pooled okio.Buffer type is used to buffer emitted ByteBuffer instances. Content of each ByteBuffer will be
* written (i.e copied) to the internal okio.Buffer slots. Once the stream terminates, the contents of all slots get
* copied to one single byte array and okio.ByteString will be created referring this byte array. Finally, the
* initial okio.Buffer will be returned to the pool.
*
* @param bbFlux the Flux of ByteBuffer to aggregate
* @return a mono emitting aggregated ByteString
*/
private static Mono<ByteString> toByteString(Flux<ByteBuffer> bbFlux) {
Objects.requireNonNull(bbFlux, "'bbFlux' cannot be null.");
return Mono.using(okio.Buffer::new,
buffer -> bbFlux.reduce(buffer, (b, byteBuffer) -> {
try {
b.write(byteBuffer);
return b;
} catch (IOException ioe) {
throw Exceptions.propagate(ioe);
}
}).map(b -> ByteString.of(b.readByteArray())), okio.Buffer::clear)
.switchIfEmpty(Mono.defer(() -> EMPTY_BYTE_STRING_MONO));
}
/**
* Aggregate InputStream to single okio.ByteString.
*
* @param inputStream the InputStream to aggregate
* @return Aggregated ByteString
*/
private static HttpResponse fromOkHttpResponse(
okhttp3.Response response, HttpRequest request, boolean eagerlyReadResponse) throws IOException {
/*
* Use a buffered response when we are eagerly reading the response from the network and the body isn't
* empty.
*/
if (eagerlyReadResponse) {
ResponseBody body = response.body();
if (Objects.nonNull(body)) {
byte[] bytes = body.bytes();
body.close();
return new OkHttpAsyncBufferedResponse(response, request, bytes);
} else {
return new OkHttpAsyncResponse(response, request);
}
} else {
return new OkHttpAsyncResponse(response, request);
}
}
private static class OkHttpCallback implements okhttp3.Callback {
private final MonoSink<HttpResponse> sink;
private final HttpRequest request;
private final boolean eagerlyReadResponse;
OkHttpCallback(MonoSink<HttpResponse> sink, HttpRequest request, boolean eagerlyReadResponse) {
this.sink = sink;
this.request = request;
this.eagerlyReadResponse = eagerlyReadResponse;
}
@SuppressWarnings("NullableProblems")
@Override
public void onFailure(okhttp3.Call call, IOException e) {
sink.error(e);
}
@SuppressWarnings("NullableProblems")
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) {
try {
HttpResponse httpResponse = fromOkHttpResponse(response, request, eagerlyReadResponse);
sink.success(httpResponse);
} catch (IOException ex) {
sink.error(ex);
}
}
}
} | class OkHttpAsyncHttpClient implements HttpClient {
private static final ClientLogger LOGGER = new ClientLogger(OkHttpAsyncHttpClient.class);
final OkHttpClient httpClient;
private static final Mono<okio.ByteString> EMPTY_BYTE_STRING_MONO = Mono.just(okio.ByteString.EMPTY);
OkHttpAsyncHttpClient(OkHttpClient httpClient) {
this.httpClient = httpClient;
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Context.NONE);
}
@Override
public Mono<HttpResponse> send(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
return Mono.create(sink -> sink.onRequest(value -> {
toOkHttpRequest(request).subscribe(okHttpRequest -> {
try {
Call call = httpClient.newCall(okHttpRequest);
call.enqueue(new OkHttpCallback(sink, request, eagerlyReadResponse));
sink.onCancel(call::cancel);
} catch (Exception ex) {
sink.error(ex);
}
}, sink::error);
}));
}
@Override
public HttpResponse sendSynchronously(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
Request okHttpRequest = toOkHttpRequestSynchronously(request);
Call call = httpClient.newCall(okHttpRequest);
try {
Response okHttpResponse = call.execute();
return fromOkHttpResponse(okHttpResponse, request, eagerlyReadResponse);
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(e));
}
}
/**
* Converts the given azure-core request to okhttp request.
*
* @param request the azure-core request
* @return the Mono emitting okhttp request
*/
private static Mono<okhttp3.Request> toOkHttpRequest(HttpRequest request) {
Request.Builder requestBuilder = new Request.Builder()
.url(request.getUrl());
if (request.getHeaders() != null) {
for (HttpHeader hdr : request.getHeaders()) {
hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value));
}
}
if (request.getHttpMethod() == HttpMethod.GET) {
return Mono.just(requestBuilder.get().build());
} else if (request.getHttpMethod() == HttpMethod.HEAD) {
return Mono.just(requestBuilder.head().build());
}
return toOkHttpRequestBody(request.getContent(), request.getHeaders())
.map(okhttpRequestBody -> requestBuilder.method(request.getHttpMethod().toString(), okhttpRequestBody)
.build());
}
/**
* Converts the given azure-core request to okhttp request.
*
* @param request the azure-core request
* @return the Mono emitting okhttp request
*/
private static okhttp3.Request toOkHttpRequestSynchronously(HttpRequest request) {
Request.Builder requestBuilder = new Request.Builder()
.url(request.getUrl());
if (request.getHeaders() != null) {
for (HttpHeader hdr : request.getHeaders()) {
hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value));
}
}
if (request.getHttpMethod() == HttpMethod.GET) {
return requestBuilder.get().build();
} else if (request.getHttpMethod() == HttpMethod.HEAD) {
return requestBuilder.head().build();
}
RequestBody requestBody = toOkHttpRequestBodySynchronously(request.getContent(), request.getHeaders());
return requestBuilder.method(request.getHttpMethod().toString(), requestBody)
.build();
}
/**
* Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux.
*
* @param bodyContent The BinaryData request body
* @param headers the headers associated with the original request
* @return the Mono emitting okhttp3.RequestBody
*/
private static RequestBody toOkHttpRequestBodySynchronously(BinaryData bodyContent, HttpHeaders headers) {
String contentType = headers.getValue("Content-Type");
MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType);
if (bodyContent == null) {
return RequestBody.create(ByteString.EMPTY, mediaType);
}
BinaryDataContent content = BinaryDataHelper.getContent(bodyContent);
if (content instanceof ByteArrayContent) {
return RequestBody.create(content.toBytes(), mediaType);
} else if (content instanceof FileContent) {
FileContent fileContent = (FileContent) content;
return RequestBody.create(fileContent.getFile().toFile(), mediaType);
} else if (content instanceof StringContent) {
return RequestBody.create(bodyContent.toString(), mediaType);
} else if (content instanceof InputStreamContent) {
return RequestBody.create(toByteString(content.toStream()), mediaType);
} else {
return toByteString(bodyContent.toFluxByteBuffer()).map(bs -> RequestBody.create(bs, mediaType)).block();
}
}
/**
* Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux.
*
* @param bodyContent The BinaryData request body
* @param headers the headers associated with the original request
* @return the Mono emitting okhttp3.RequestBody
*/
private static Mono<RequestBody> toOkHttpRequestBody(BinaryData bodyContent, HttpHeaders headers) {
String contentType = headers.getValue("Content-Type");
MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType);
if (bodyContent == null) {
return Mono.defer(() -> Mono.just(RequestBody.create(ByteString.EMPTY, mediaType)));
}
BinaryDataContent content = BinaryDataHelper.getContent(bodyContent);
if (content instanceof ByteArrayContent) {
return Mono.defer(() -> Mono.just(RequestBody.create(content.toBytes(), mediaType)));
} else if (content instanceof FileContent) {
FileContent fileContent = (FileContent) content;
return Mono.defer(() -> Mono.just(RequestBody.create(fileContent.getFile().toFile(), mediaType)));
} else if (content instanceof StringContent) {
return Mono.defer(() -> Mono.just(RequestBody.create(bodyContent.toString(), mediaType)));
} else {
return toByteString(bodyContent.toFluxByteBuffer()).map(bs -> RequestBody.create(bs, mediaType));
}
}
/**
* Aggregate Flux of java.nio.ByteBuffer to single okio.ByteString.
*
* Pooled okio.Buffer type is used to buffer emitted ByteBuffer instances. Content of each ByteBuffer will be
* written (i.e copied) to the internal okio.Buffer slots. Once the stream terminates, the contents of all slots get
* copied to one single byte array and okio.ByteString will be created referring this byte array. Finally, the
* initial okio.Buffer will be returned to the pool.
*
* @param bbFlux the Flux of ByteBuffer to aggregate
* @return a mono emitting aggregated ByteString
*/
private static Mono<ByteString> toByteString(Flux<ByteBuffer> bbFlux) {
Objects.requireNonNull(bbFlux, "'bbFlux' cannot be null.");
return Mono.using(okio.Buffer::new,
buffer -> bbFlux.reduce(buffer, (b, byteBuffer) -> {
try {
b.write(byteBuffer);
return b;
} catch (IOException ioe) {
throw Exceptions.propagate(ioe);
}
}).map(b -> ByteString.of(b.readByteArray())), okio.Buffer::clear)
.switchIfEmpty(Mono.defer(() -> EMPTY_BYTE_STRING_MONO));
}
/**
* Aggregate InputStream to single okio.ByteString.
*
* @param inputStream the InputStream to aggregate
* @return Aggregated ByteString
*/
private static HttpResponse fromOkHttpResponse(
okhttp3.Response response, HttpRequest request, boolean eagerlyReadResponse) throws IOException {
/*
* Use a buffered response when we are eagerly reading the response from the network and the body isn't
* empty.
*/
if (eagerlyReadResponse) {
ResponseBody body = response.body();
if (Objects.nonNull(body)) {
byte[] bytes = body.bytes();
body.close();
return new OkHttpAsyncBufferedResponse(response, request, bytes);
} else {
return new OkHttpAsyncResponse(response, request);
}
} else {
return new OkHttpAsyncResponse(response, request);
}
}
private static class OkHttpCallback implements okhttp3.Callback {
private final MonoSink<HttpResponse> sink;
private final HttpRequest request;
private final boolean eagerlyReadResponse;
OkHttpCallback(MonoSink<HttpResponse> sink, HttpRequest request, boolean eagerlyReadResponse) {
this.sink = sink;
this.request = request;
this.eagerlyReadResponse = eagerlyReadResponse;
}
@SuppressWarnings("NullableProblems")
@Override
public void onFailure(okhttp3.Call call, IOException e) {
sink.error(e);
}
@SuppressWarnings("NullableProblems")
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) {
try {
HttpResponse httpResponse = fromOkHttpResponse(response, request, eagerlyReadResponse);
sink.success(httpResponse);
} catch (IOException ex) {
sink.error(ex);
}
}
}
} |
yeah, that be neat. There's `InputStream.readAllBytes()` with some interesting code since Java 11. So I guess it'd be something like we have for reflections perhaps. | private static ByteString toByteString(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int nRead;
byte[] buffer = new byte[8192];
try (InputStream closeableInputStream = inputStream) {
while ((nRead = closeableInputStream.read(buffer, 0, buffer.length)) != -1) {
outputStream.write(buffer, 0, nRead);
}
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(e));
}
return ByteString.of(outputStream.toByteArray());
} | try (InputStream closeableInputStream = inputStream) { | private static ByteString toByteString(InputStream inputStream) {
try (InputStream closeableInputStream = inputStream) {
byte[] content = StreamUtils.INSTANCE.readAllBytes(closeableInputStream);
return ByteString.of(content);
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(e));
}
} | class OkHttpAsyncHttpClient implements HttpClient {
private static final ClientLogger LOGGER = new ClientLogger(OkHttpAsyncHttpClient.class);
final OkHttpClient httpClient;
private static final Mono<okio.ByteString> EMPTY_BYTE_STRING_MONO = Mono.just(okio.ByteString.EMPTY);
OkHttpAsyncHttpClient(OkHttpClient httpClient) {
this.httpClient = httpClient;
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Context.NONE);
}
@Override
public Mono<HttpResponse> send(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
return Mono.create(sink -> sink.onRequest(value -> {
toOkHttpRequest(request).subscribe(okHttpRequest -> {
try {
Call call = httpClient.newCall(okHttpRequest);
call.enqueue(new OkHttpCallback(sink, request, eagerlyReadResponse));
sink.onCancel(call::cancel);
} catch (Exception ex) {
sink.error(ex);
}
}, sink::error);
}));
}
@Override
public HttpResponse sendSynchronously(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
Request okHttpRequest = toOkHttpRequestSynchronously(request);
Call call = httpClient.newCall(okHttpRequest);
try {
Response okHttpResponse = call.execute();
return fromOkHttpResponse(okHttpResponse, request, eagerlyReadResponse);
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(e));
}
}
/**
* Converts the given azure-core request to okhttp request.
*
* @param request the azure-core request
* @return the Mono emitting okhttp request
*/
private static Mono<okhttp3.Request> toOkHttpRequest(HttpRequest request) {
Request.Builder requestBuilder = new Request.Builder()
.url(request.getUrl());
if (request.getHeaders() != null) {
for (HttpHeader hdr : request.getHeaders()) {
hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value));
}
}
if (request.getHttpMethod() == HttpMethod.GET) {
return Mono.just(requestBuilder.get().build());
} else if (request.getHttpMethod() == HttpMethod.HEAD) {
return Mono.just(requestBuilder.head().build());
}
return toOkHttpRequestBody(request.getContent(), request.getHeaders())
.map(okhttpRequestBody -> requestBuilder.method(request.getHttpMethod().toString(), okhttpRequestBody)
.build());
}
/**
* Converts the given azure-core request to okhttp request.
*
* @param request the azure-core request
* @return the Mono emitting okhttp request
*/
private static okhttp3.Request toOkHttpRequestSynchronously(HttpRequest request) {
Request.Builder requestBuilder = new Request.Builder()
.url(request.getUrl());
if (request.getHeaders() != null) {
for (HttpHeader hdr : request.getHeaders()) {
hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value));
}
}
if (request.getHttpMethod() == HttpMethod.GET) {
return requestBuilder.get().build();
} else if (request.getHttpMethod() == HttpMethod.HEAD) {
return requestBuilder.head().build();
}
RequestBody requestBody = toOkHttpRequestBodySynchronously(request.getContent(), request.getHeaders());
return requestBuilder.method(request.getHttpMethod().toString(), requestBody)
.build();
}
/**
* Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux.
*
* @param bodyContent The BinaryData request body
* @param headers the headers associated with the original request
* @return the Mono emitting okhttp3.RequestBody
*/
private static RequestBody toOkHttpRequestBodySynchronously(BinaryData bodyContent, HttpHeaders headers) {
String contentType = headers.getValue("Content-Type");
MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType);
if (bodyContent == null) {
return RequestBody.create(ByteString.EMPTY, mediaType);
}
BinaryDataContent content = BinaryDataHelper.getContent(bodyContent);
if (content instanceof ByteArrayContent) {
return RequestBody.create(content.toBytes(), mediaType);
} else if (content instanceof FileContent) {
FileContent fileContent = (FileContent) content;
return RequestBody.create(fileContent.getFile().toFile(), mediaType);
} else if (content instanceof StringContent) {
return RequestBody.create(bodyContent.toString(), mediaType);
} else if (content instanceof InputStreamContent) {
return RequestBody.create(toByteString(content.toStream()), mediaType);
} else {
return toByteString(bodyContent.toFluxByteBuffer()).map(bs -> RequestBody.create(bs, mediaType)).block();
}
}
/**
* Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux.
*
* @param bodyContent The BinaryData request body
* @param headers the headers associated with the original request
* @return the Mono emitting okhttp3.RequestBody
*/
private static Mono<RequestBody> toOkHttpRequestBody(BinaryData bodyContent, HttpHeaders headers) {
String contentType = headers.getValue("Content-Type");
MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType);
if (bodyContent == null) {
return Mono.defer(() -> Mono.just(RequestBody.create(ByteString.EMPTY, mediaType)));
}
BinaryDataContent content = BinaryDataHelper.getContent(bodyContent);
if (content instanceof ByteArrayContent) {
return Mono.defer(() -> Mono.just(RequestBody.create(content.toBytes(), mediaType)));
} else if (content instanceof FileContent) {
FileContent fileContent = (FileContent) content;
return Mono.defer(() -> Mono.just(RequestBody.create(fileContent.getFile().toFile(), mediaType)));
} else if (content instanceof StringContent) {
return Mono.defer(() -> Mono.just(RequestBody.create(bodyContent.toString(), mediaType)));
} else {
return toByteString(bodyContent.toFluxByteBuffer()).map(bs -> RequestBody.create(bs, mediaType));
}
}
/**
* Aggregate Flux of java.nio.ByteBuffer to single okio.ByteString.
*
* Pooled okio.Buffer type is used to buffer emitted ByteBuffer instances. Content of each ByteBuffer will be
* written (i.e copied) to the internal okio.Buffer slots. Once the stream terminates, the contents of all slots get
* copied to one single byte array and okio.ByteString will be created referring this byte array. Finally, the
* initial okio.Buffer will be returned to the pool.
*
* @param bbFlux the Flux of ByteBuffer to aggregate
* @return a mono emitting aggregated ByteString
*/
private static Mono<ByteString> toByteString(Flux<ByteBuffer> bbFlux) {
Objects.requireNonNull(bbFlux, "'bbFlux' cannot be null.");
return Mono.using(okio.Buffer::new,
buffer -> bbFlux.reduce(buffer, (b, byteBuffer) -> {
try {
b.write(byteBuffer);
return b;
} catch (IOException ioe) {
throw Exceptions.propagate(ioe);
}
}).map(b -> ByteString.of(b.readByteArray())), okio.Buffer::clear)
.switchIfEmpty(Mono.defer(() -> EMPTY_BYTE_STRING_MONO));
}
/**
* Aggregate InputStream to single okio.ByteString.
*
* @param inputStream the InputStream to aggregate
* @return Aggregated ByteString
*/
private static HttpResponse fromOkHttpResponse(
okhttp3.Response response, HttpRequest request, boolean eagerlyReadResponse) throws IOException {
/*
* Use a buffered response when we are eagerly reading the response from the network and the body isn't
* empty.
*/
if (eagerlyReadResponse) {
ResponseBody body = response.body();
if (Objects.nonNull(body)) {
byte[] bytes = body.bytes();
body.close();
return new OkHttpAsyncBufferedResponse(response, request, bytes);
} else {
return new OkHttpAsyncResponse(response, request);
}
} else {
return new OkHttpAsyncResponse(response, request);
}
}
private static class OkHttpCallback implements okhttp3.Callback {
private final MonoSink<HttpResponse> sink;
private final HttpRequest request;
private final boolean eagerlyReadResponse;
OkHttpCallback(MonoSink<HttpResponse> sink, HttpRequest request, boolean eagerlyReadResponse) {
this.sink = sink;
this.request = request;
this.eagerlyReadResponse = eagerlyReadResponse;
}
@SuppressWarnings("NullableProblems")
@Override
public void onFailure(okhttp3.Call call, IOException e) {
sink.error(e);
}
@SuppressWarnings("NullableProblems")
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) {
try {
HttpResponse httpResponse = fromOkHttpResponse(response, request, eagerlyReadResponse);
sink.success(httpResponse);
} catch (IOException ex) {
sink.error(ex);
}
}
}
} | class OkHttpAsyncHttpClient implements HttpClient {
private static final ClientLogger LOGGER = new ClientLogger(OkHttpAsyncHttpClient.class);
final OkHttpClient httpClient;
private static final Mono<okio.ByteString> EMPTY_BYTE_STRING_MONO = Mono.just(okio.ByteString.EMPTY);
OkHttpAsyncHttpClient(OkHttpClient httpClient) {
this.httpClient = httpClient;
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Context.NONE);
}
@Override
public Mono<HttpResponse> send(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
return Mono.create(sink -> sink.onRequest(value -> {
toOkHttpRequest(request).subscribe(okHttpRequest -> {
try {
Call call = httpClient.newCall(okHttpRequest);
call.enqueue(new OkHttpCallback(sink, request, eagerlyReadResponse));
sink.onCancel(call::cancel);
} catch (Exception ex) {
sink.error(ex);
}
}, sink::error);
}));
}
@Override
public HttpResponse sendSynchronously(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
Request okHttpRequest = toOkHttpRequestSynchronously(request);
Call call = httpClient.newCall(okHttpRequest);
try {
Response okHttpResponse = call.execute();
return fromOkHttpResponse(okHttpResponse, request, eagerlyReadResponse);
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(e));
}
}
/**
* Converts the given azure-core request to okhttp request.
*
* @param request the azure-core request
* @return the Mono emitting okhttp request
*/
private static Mono<okhttp3.Request> toOkHttpRequest(HttpRequest request) {
Request.Builder requestBuilder = new Request.Builder()
.url(request.getUrl());
if (request.getHeaders() != null) {
for (HttpHeader hdr : request.getHeaders()) {
hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value));
}
}
if (request.getHttpMethod() == HttpMethod.GET) {
return Mono.just(requestBuilder.get().build());
} else if (request.getHttpMethod() == HttpMethod.HEAD) {
return Mono.just(requestBuilder.head().build());
}
return toOkHttpRequestBody(request.getContent(), request.getHeaders())
.map(okhttpRequestBody -> requestBuilder.method(request.getHttpMethod().toString(), okhttpRequestBody)
.build());
}
/**
* Converts the given azure-core request to okhttp request.
*
* @param request the azure-core request
* @return the Mono emitting okhttp request
*/
private static okhttp3.Request toOkHttpRequestSynchronously(HttpRequest request) {
Request.Builder requestBuilder = new Request.Builder()
.url(request.getUrl());
if (request.getHeaders() != null) {
for (HttpHeader hdr : request.getHeaders()) {
hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value));
}
}
if (request.getHttpMethod() == HttpMethod.GET) {
return requestBuilder.get().build();
} else if (request.getHttpMethod() == HttpMethod.HEAD) {
return requestBuilder.head().build();
}
RequestBody requestBody = toOkHttpRequestBodySynchronously(request.getContent(), request.getHeaders());
return requestBuilder.method(request.getHttpMethod().toString(), requestBody)
.build();
}
/**
* Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux.
*
* @param bodyContent The BinaryData request body
* @param headers the headers associated with the original request
* @return the Mono emitting okhttp3.RequestBody
*/
private static RequestBody toOkHttpRequestBodySynchronously(BinaryData bodyContent, HttpHeaders headers) {
String contentType = headers.getValue("Content-Type");
MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType);
if (bodyContent == null) {
return RequestBody.create(ByteString.EMPTY, mediaType);
}
BinaryDataContent content = BinaryDataHelper.getContent(bodyContent);
if (content instanceof ByteArrayContent) {
return RequestBody.create(content.toBytes(), mediaType);
} else if (content instanceof FileContent) {
FileContent fileContent = (FileContent) content;
return RequestBody.create(fileContent.getFile().toFile(), mediaType);
} else if (content instanceof StringContent) {
return RequestBody.create(bodyContent.toString(), mediaType);
} else if (content instanceof InputStreamContent) {
return RequestBody.create(toByteString(content.toStream()), mediaType);
} else {
return toByteString(bodyContent.toFluxByteBuffer()).map(bs -> RequestBody.create(bs, mediaType)).block();
}
}
/**
* Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux.
*
* @param bodyContent The BinaryData request body
* @param headers the headers associated with the original request
* @return the Mono emitting okhttp3.RequestBody
*/
private static Mono<RequestBody> toOkHttpRequestBody(BinaryData bodyContent, HttpHeaders headers) {
String contentType = headers.getValue("Content-Type");
MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType);
if (bodyContent == null) {
return Mono.defer(() -> Mono.just(RequestBody.create(ByteString.EMPTY, mediaType)));
}
BinaryDataContent content = BinaryDataHelper.getContent(bodyContent);
if (content instanceof ByteArrayContent) {
return Mono.defer(() -> Mono.just(RequestBody.create(content.toBytes(), mediaType)));
} else if (content instanceof FileContent) {
FileContent fileContent = (FileContent) content;
return Mono.defer(() -> Mono.just(RequestBody.create(fileContent.getFile().toFile(), mediaType)));
} else if (content instanceof StringContent) {
return Mono.defer(() -> Mono.just(RequestBody.create(bodyContent.toString(), mediaType)));
} else {
return toByteString(bodyContent.toFluxByteBuffer()).map(bs -> RequestBody.create(bs, mediaType));
}
}
/**
* Aggregate Flux of java.nio.ByteBuffer to single okio.ByteString.
*
* Pooled okio.Buffer type is used to buffer emitted ByteBuffer instances. Content of each ByteBuffer will be
* written (i.e copied) to the internal okio.Buffer slots. Once the stream terminates, the contents of all slots get
* copied to one single byte array and okio.ByteString will be created referring this byte array. Finally, the
* initial okio.Buffer will be returned to the pool.
*
* @param bbFlux the Flux of ByteBuffer to aggregate
* @return a mono emitting aggregated ByteString
*/
private static Mono<ByteString> toByteString(Flux<ByteBuffer> bbFlux) {
Objects.requireNonNull(bbFlux, "'bbFlux' cannot be null.");
return Mono.using(okio.Buffer::new,
buffer -> bbFlux.reduce(buffer, (b, byteBuffer) -> {
try {
b.write(byteBuffer);
return b;
} catch (IOException ioe) {
throw Exceptions.propagate(ioe);
}
}).map(b -> ByteString.of(b.readByteArray())), okio.Buffer::clear)
.switchIfEmpty(Mono.defer(() -> EMPTY_BYTE_STRING_MONO));
}
/**
* Aggregate InputStream to single okio.ByteString.
*
* @param inputStream the InputStream to aggregate
* @return Aggregated ByteString
*/
private static HttpResponse fromOkHttpResponse(
okhttp3.Response response, HttpRequest request, boolean eagerlyReadResponse) throws IOException {
/*
* Use a buffered response when we are eagerly reading the response from the network and the body isn't
* empty.
*/
if (eagerlyReadResponse) {
ResponseBody body = response.body();
if (Objects.nonNull(body)) {
byte[] bytes = body.bytes();
body.close();
return new OkHttpAsyncBufferedResponse(response, request, bytes);
} else {
return new OkHttpAsyncResponse(response, request);
}
} else {
return new OkHttpAsyncResponse(response, request);
}
}
private static class OkHttpCallback implements okhttp3.Callback {
private final MonoSink<HttpResponse> sink;
private final HttpRequest request;
private final boolean eagerlyReadResponse;
OkHttpCallback(MonoSink<HttpResponse> sink, HttpRequest request, boolean eagerlyReadResponse) {
this.sink = sink;
this.request = request;
this.eagerlyReadResponse = eagerlyReadResponse;
}
@SuppressWarnings("NullableProblems")
@Override
public void onFailure(okhttp3.Call call, IOException e) {
sink.error(e);
}
@SuppressWarnings("NullableProblems")
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) {
try {
HttpResponse httpResponse = fromOkHttpResponse(response, request, eagerlyReadResponse);
sink.success(httpResponse);
} catch (IOException ex) {
sink.error(ex);
}
}
}
} |
Sounds interesting. I'll add that to todo. | private static RequestBody toOkHttpRequestBodySynchronously(BinaryData bodyContent, HttpHeaders headers) {
String contentType = headers.getValue("Content-Type");
MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType);
if (bodyContent == null) {
return RequestBody.create(ByteString.EMPTY, mediaType);
}
BinaryDataContent content = BinaryDataHelper.getContent(bodyContent);
if (content instanceof ByteArrayContent) {
return RequestBody.create(content.toBytes(), mediaType);
} else if (content instanceof FileContent) {
FileContent fileContent = (FileContent) content;
return RequestBody.create(fileContent.getFile().toFile(), mediaType);
} else if (content instanceof StringContent) {
return RequestBody.create(bodyContent.toString(), mediaType);
} else if (content instanceof InputStreamContent) {
return RequestBody.create(toByteString(content.toStream()), mediaType);
} else {
return toByteString(bodyContent.toFluxByteBuffer()).map(bs -> RequestBody.create(bs, mediaType)).block();
}
} | private static RequestBody toOkHttpRequestBodySynchronously(BinaryData bodyContent, HttpHeaders headers) {
String contentType = headers.getValue("Content-Type");
MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType);
if (bodyContent == null) {
return RequestBody.create(ByteString.EMPTY, mediaType);
}
BinaryDataContent content = BinaryDataHelper.getContent(bodyContent);
if (content instanceof ByteArrayContent) {
return RequestBody.create(content.toBytes(), mediaType);
} else if (content instanceof FileContent) {
FileContent fileContent = (FileContent) content;
return RequestBody.create(fileContent.getFile().toFile(), mediaType);
} else if (content instanceof StringContent) {
return RequestBody.create(bodyContent.toString(), mediaType);
} else if (content instanceof InputStreamContent) {
return RequestBody.create(toByteString(content.toStream()), mediaType);
} else {
return toByteString(bodyContent.toFluxByteBuffer()).map(bs -> RequestBody.create(bs, mediaType)).block();
}
} | class OkHttpAsyncHttpClient implements HttpClient {
private static final ClientLogger LOGGER = new ClientLogger(OkHttpAsyncHttpClient.class);
final OkHttpClient httpClient;
private static final Mono<okio.ByteString> EMPTY_BYTE_STRING_MONO = Mono.just(okio.ByteString.EMPTY);
OkHttpAsyncHttpClient(OkHttpClient httpClient) {
this.httpClient = httpClient;
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Context.NONE);
}
@Override
public Mono<HttpResponse> send(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
return Mono.create(sink -> sink.onRequest(value -> {
toOkHttpRequest(request).subscribe(okHttpRequest -> {
try {
Call call = httpClient.newCall(okHttpRequest);
call.enqueue(new OkHttpCallback(sink, request, eagerlyReadResponse));
sink.onCancel(call::cancel);
} catch (Exception ex) {
sink.error(ex);
}
}, sink::error);
}));
}
@Override
public HttpResponse sendSynchronously(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
Request okHttpRequest = toOkHttpRequestSynchronously(request);
Call call = httpClient.newCall(okHttpRequest);
try {
Response okHttpResponse = call.execute();
return fromOkHttpResponse(okHttpResponse, request, eagerlyReadResponse);
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(e));
}
}
/**
* Converts the given azure-core request to okhttp request.
*
* @param request the azure-core request
* @return the Mono emitting okhttp request
*/
private static Mono<okhttp3.Request> toOkHttpRequest(HttpRequest request) {
Request.Builder requestBuilder = new Request.Builder()
.url(request.getUrl());
if (request.getHeaders() != null) {
for (HttpHeader hdr : request.getHeaders()) {
hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value));
}
}
if (request.getHttpMethod() == HttpMethod.GET) {
return Mono.just(requestBuilder.get().build());
} else if (request.getHttpMethod() == HttpMethod.HEAD) {
return Mono.just(requestBuilder.head().build());
}
return toOkHttpRequestBody(request.getContent(), request.getHeaders())
.map(okhttpRequestBody -> requestBuilder.method(request.getHttpMethod().toString(), okhttpRequestBody)
.build());
}
/**
* Converts the given azure-core request to okhttp request.
*
* @param request the azure-core request
* @return the Mono emitting okhttp request
*/
private static okhttp3.Request toOkHttpRequestSynchronously(HttpRequest request) {
Request.Builder requestBuilder = new Request.Builder()
.url(request.getUrl());
if (request.getHeaders() != null) {
for (HttpHeader hdr : request.getHeaders()) {
hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value));
}
}
if (request.getHttpMethod() == HttpMethod.GET) {
return requestBuilder.get().build();
} else if (request.getHttpMethod() == HttpMethod.HEAD) {
return requestBuilder.head().build();
}
RequestBody requestBody = toOkHttpRequestBodySynchronously(request.getContent(), request.getHeaders());
return requestBuilder.method(request.getHttpMethod().toString(), requestBody)
.build();
}
/**
* Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux.
*
* @param bodyContent The BinaryData request body
* @param headers the headers associated with the original request
* @return the Mono emitting okhttp3.RequestBody
*/
/**
* Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux.
*
* @param bodyContent The BinaryData request body
* @param headers the headers associated with the original request
* @return the Mono emitting okhttp3.RequestBody
*/
private static Mono<RequestBody> toOkHttpRequestBody(BinaryData bodyContent, HttpHeaders headers) {
String contentType = headers.getValue("Content-Type");
MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType);
if (bodyContent == null) {
return Mono.defer(() -> Mono.just(RequestBody.create(ByteString.EMPTY, mediaType)));
}
BinaryDataContent content = BinaryDataHelper.getContent(bodyContent);
if (content instanceof ByteArrayContent) {
return Mono.defer(() -> Mono.just(RequestBody.create(content.toBytes(), mediaType)));
} else if (content instanceof FileContent) {
FileContent fileContent = (FileContent) content;
return Mono.defer(() -> Mono.just(RequestBody.create(fileContent.getFile().toFile(), mediaType)));
} else if (content instanceof StringContent) {
return Mono.defer(() -> Mono.just(RequestBody.create(bodyContent.toString(), mediaType)));
} else {
return toByteString(bodyContent.toFluxByteBuffer()).map(bs -> RequestBody.create(bs, mediaType));
}
}
/**
* Aggregate Flux of java.nio.ByteBuffer to single okio.ByteString.
*
* Pooled okio.Buffer type is used to buffer emitted ByteBuffer instances. Content of each ByteBuffer will be
* written (i.e copied) to the internal okio.Buffer slots. Once the stream terminates, the contents of all slots get
* copied to one single byte array and okio.ByteString will be created referring this byte array. Finally, the
* initial okio.Buffer will be returned to the pool.
*
* @param bbFlux the Flux of ByteBuffer to aggregate
* @return a mono emitting aggregated ByteString
*/
private static Mono<ByteString> toByteString(Flux<ByteBuffer> bbFlux) {
Objects.requireNonNull(bbFlux, "'bbFlux' cannot be null.");
return Mono.using(okio.Buffer::new,
buffer -> bbFlux.reduce(buffer, (b, byteBuffer) -> {
try {
b.write(byteBuffer);
return b;
} catch (IOException ioe) {
throw Exceptions.propagate(ioe);
}
}).map(b -> ByteString.of(b.readByteArray())), okio.Buffer::clear)
.switchIfEmpty(Mono.defer(() -> EMPTY_BYTE_STRING_MONO));
}
/**
* Aggregate InputStream to single okio.ByteString.
*
* @param inputStream the InputStream to aggregate
* @return Aggregated ByteString
*/
private static ByteString toByteString(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int nRead;
byte[] buffer = new byte[8192];
try (InputStream closeableInputStream = inputStream) {
while ((nRead = closeableInputStream.read(buffer, 0, buffer.length)) != -1) {
outputStream.write(buffer, 0, nRead);
}
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(e));
}
return ByteString.of(outputStream.toByteArray());
}
private static HttpResponse fromOkHttpResponse(
okhttp3.Response response, HttpRequest request, boolean eagerlyReadResponse) throws IOException {
/*
* Use a buffered response when we are eagerly reading the response from the network and the body isn't
* empty.
*/
if (eagerlyReadResponse) {
ResponseBody body = response.body();
if (Objects.nonNull(body)) {
byte[] bytes = body.bytes();
body.close();
return new OkHttpAsyncBufferedResponse(response, request, bytes);
} else {
return new OkHttpAsyncResponse(response, request);
}
} else {
return new OkHttpAsyncResponse(response, request);
}
}
private static class OkHttpCallback implements okhttp3.Callback {
private final MonoSink<HttpResponse> sink;
private final HttpRequest request;
private final boolean eagerlyReadResponse;
OkHttpCallback(MonoSink<HttpResponse> sink, HttpRequest request, boolean eagerlyReadResponse) {
this.sink = sink;
this.request = request;
this.eagerlyReadResponse = eagerlyReadResponse;
}
@SuppressWarnings("NullableProblems")
@Override
public void onFailure(okhttp3.Call call, IOException e) {
sink.error(e);
}
@SuppressWarnings("NullableProblems")
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) {
try {
HttpResponse httpResponse = fromOkHttpResponse(response, request, eagerlyReadResponse);
sink.success(httpResponse);
} catch (IOException ex) {
sink.error(ex);
}
}
}
} | class OkHttpAsyncHttpClient implements HttpClient {
private static final ClientLogger LOGGER = new ClientLogger(OkHttpAsyncHttpClient.class);
final OkHttpClient httpClient;
private static final Mono<okio.ByteString> EMPTY_BYTE_STRING_MONO = Mono.just(okio.ByteString.EMPTY);
OkHttpAsyncHttpClient(OkHttpClient httpClient) {
this.httpClient = httpClient;
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Context.NONE);
}
@Override
public Mono<HttpResponse> send(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
return Mono.create(sink -> sink.onRequest(value -> {
toOkHttpRequest(request).subscribe(okHttpRequest -> {
try {
Call call = httpClient.newCall(okHttpRequest);
call.enqueue(new OkHttpCallback(sink, request, eagerlyReadResponse));
sink.onCancel(call::cancel);
} catch (Exception ex) {
sink.error(ex);
}
}, sink::error);
}));
}
@Override
public HttpResponse sendSynchronously(HttpRequest request, Context context) {
boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false);
Request okHttpRequest = toOkHttpRequestSynchronously(request);
Call call = httpClient.newCall(okHttpRequest);
try {
Response okHttpResponse = call.execute();
return fromOkHttpResponse(okHttpResponse, request, eagerlyReadResponse);
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(e));
}
}
/**
* Converts the given azure-core request to okhttp request.
*
* @param request the azure-core request
* @return the Mono emitting okhttp request
*/
private static Mono<okhttp3.Request> toOkHttpRequest(HttpRequest request) {
Request.Builder requestBuilder = new Request.Builder()
.url(request.getUrl());
if (request.getHeaders() != null) {
for (HttpHeader hdr : request.getHeaders()) {
hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value));
}
}
if (request.getHttpMethod() == HttpMethod.GET) {
return Mono.just(requestBuilder.get().build());
} else if (request.getHttpMethod() == HttpMethod.HEAD) {
return Mono.just(requestBuilder.head().build());
}
return toOkHttpRequestBody(request.getContent(), request.getHeaders())
.map(okhttpRequestBody -> requestBuilder.method(request.getHttpMethod().toString(), okhttpRequestBody)
.build());
}
/**
* Converts the given azure-core request to okhttp request.
*
* @param request the azure-core request
* @return the Mono emitting okhttp request
*/
private static okhttp3.Request toOkHttpRequestSynchronously(HttpRequest request) {
Request.Builder requestBuilder = new Request.Builder()
.url(request.getUrl());
if (request.getHeaders() != null) {
for (HttpHeader hdr : request.getHeaders()) {
hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value));
}
}
if (request.getHttpMethod() == HttpMethod.GET) {
return requestBuilder.get().build();
} else if (request.getHttpMethod() == HttpMethod.HEAD) {
return requestBuilder.head().build();
}
RequestBody requestBody = toOkHttpRequestBodySynchronously(request.getContent(), request.getHeaders());
return requestBuilder.method(request.getHttpMethod().toString(), requestBody)
.build();
}
/**
* Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux.
*
* @param bodyContent The BinaryData request body
* @param headers the headers associated with the original request
* @return the Mono emitting okhttp3.RequestBody
*/
/**
* Create a Mono of okhttp3.RequestBody from the given java.nio.ByteBuffer Flux.
*
* @param bodyContent The BinaryData request body
* @param headers the headers associated with the original request
* @return the Mono emitting okhttp3.RequestBody
*/
private static Mono<RequestBody> toOkHttpRequestBody(BinaryData bodyContent, HttpHeaders headers) {
String contentType = headers.getValue("Content-Type");
MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType);
if (bodyContent == null) {
return Mono.defer(() -> Mono.just(RequestBody.create(ByteString.EMPTY, mediaType)));
}
BinaryDataContent content = BinaryDataHelper.getContent(bodyContent);
if (content instanceof ByteArrayContent) {
return Mono.defer(() -> Mono.just(RequestBody.create(content.toBytes(), mediaType)));
} else if (content instanceof FileContent) {
FileContent fileContent = (FileContent) content;
return Mono.defer(() -> Mono.just(RequestBody.create(fileContent.getFile().toFile(), mediaType)));
} else if (content instanceof StringContent) {
return Mono.defer(() -> Mono.just(RequestBody.create(bodyContent.toString(), mediaType)));
} else {
return toByteString(bodyContent.toFluxByteBuffer()).map(bs -> RequestBody.create(bs, mediaType));
}
}
/**
* Aggregate Flux of java.nio.ByteBuffer to single okio.ByteString.
*
* Pooled okio.Buffer type is used to buffer emitted ByteBuffer instances. Content of each ByteBuffer will be
* written (i.e copied) to the internal okio.Buffer slots. Once the stream terminates, the contents of all slots get
* copied to one single byte array and okio.ByteString will be created referring this byte array. Finally, the
* initial okio.Buffer will be returned to the pool.
*
* @param bbFlux the Flux of ByteBuffer to aggregate
* @return a mono emitting aggregated ByteString
*/
private static Mono<ByteString> toByteString(Flux<ByteBuffer> bbFlux) {
Objects.requireNonNull(bbFlux, "'bbFlux' cannot be null.");
return Mono.using(okio.Buffer::new,
buffer -> bbFlux.reduce(buffer, (b, byteBuffer) -> {
try {
b.write(byteBuffer);
return b;
} catch (IOException ioe) {
throw Exceptions.propagate(ioe);
}
}).map(b -> ByteString.of(b.readByteArray())), okio.Buffer::clear)
.switchIfEmpty(Mono.defer(() -> EMPTY_BYTE_STRING_MONO));
}
/**
* Aggregate InputStream to single okio.ByteString.
*
* @param inputStream the InputStream to aggregate
* @return Aggregated ByteString
*/
private static ByteString toByteString(InputStream inputStream) {
try (InputStream closeableInputStream = inputStream) {
byte[] content = StreamUtils.INSTANCE.readAllBytes(closeableInputStream);
return ByteString.of(content);
} catch (IOException e) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(e));
}
}
private static HttpResponse fromOkHttpResponse(
okhttp3.Response response, HttpRequest request, boolean eagerlyReadResponse) throws IOException {
/*
* Use a buffered response when we are eagerly reading the response from the network and the body isn't
* empty.
*/
if (eagerlyReadResponse) {
ResponseBody body = response.body();
if (Objects.nonNull(body)) {
byte[] bytes = body.bytes();
body.close();
return new OkHttpAsyncBufferedResponse(response, request, bytes);
} else {
return new OkHttpAsyncResponse(response, request);
}
} else {
return new OkHttpAsyncResponse(response, request);
}
}
private static class OkHttpCallback implements okhttp3.Callback {
private final MonoSink<HttpResponse> sink;
private final HttpRequest request;
private final boolean eagerlyReadResponse;
OkHttpCallback(MonoSink<HttpResponse> sink, HttpRequest request, boolean eagerlyReadResponse) {
this.sink = sink;
this.request = request;
this.eagerlyReadResponse = eagerlyReadResponse;
}
@SuppressWarnings("NullableProblems")
@Override
public void onFailure(okhttp3.Call call, IOException e) {
sink.error(e);
}
@SuppressWarnings("NullableProblems")
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) {
try {
HttpResponse httpResponse = fromOkHttpResponse(response, request, eagerlyReadResponse);
sink.success(httpResponse);
} catch (IOException ex) {
sink.error(ex);
}
}
}
} | |
just trying to understand since I see this update all over the PR, was DocumentBuildMode just missing from before / is now replacing the removed modelId? | public void beginBuildModel() {
String trainingFilesUrl = "{SAS-URL-of-your-container-in-blob-storage}";
documentModelAdministrationAsyncClient.beginBuildModel(trainingFilesUrl, DocumentBuildMode.TEMPLATE
)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
} | public void beginBuildModel() {
String trainingFilesUrl = "{SAS-URL-of-your-container-in-blob-storage}";
documentModelAdministrationAsyncClient.beginBuildModel(trainingFilesUrl, DocumentBuildMode.TEMPLATE
)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
} | class DocumentModelAdminAsyncClientJavaDocCodeSnippets {
private final DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient =
new DocumentModelAdministrationClientBuilder().buildAsyncClient();
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient} initialization
*/
public void formTrainingAsyncClientInInitialization() {
DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient =
new DocumentModelAdministrationClientBuilder().buildAsyncClient();
}
/**
* Code snippet for creating a {@link DocumentModelAdministrationAsyncClient} with pipeline
*/
public void createDocumentTrainingAsyncClientWithPipeline() {
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(/* add policies */)
.build();
DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient =
new DocumentModelAdministrationClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.pipeline(pipeline)
.buildAsyncClient();
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
* with options
*/
public void beginBuildModelWithOptions() {
String trainingFilesUrl = "{SAS-URL-of-your-container-in-blob-storage}";
Map<String, String> attrs = new HashMap<String, String>();
attrs.put("createdBy", "sample");
documentModelAdministrationAsyncClient.beginBuildModel(trainingFilesUrl,
DocumentBuildMode.TEMPLATE,
new BuildModelOptions()
.setDescription("model desc")
.setPrefix("Invoice")
.setTags(attrs))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Description: %s%n", documentModel.getDescription());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
System.out.printf("Model assigned tags: %s%n", documentModel.getTags());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void deleteModel() {
String modelId = "{model_id}";
documentModelAdministrationAsyncClient.deleteModel(modelId)
.subscribe(ignored -> System.out.printf("Model ID: %s is deleted%n", modelId));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void deleteModelWithResponse() {
String modelId = "{model_id}";
documentModelAdministrationAsyncClient.deleteModelWithResponse(modelId)
.subscribe(response -> {
System.out.printf("Response Status Code: %d.", response.getStatusCode());
System.out.printf("Model ID: %s is deleted.%n", modelId);
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getCopyAuthorization() {
String modelId = "my-copied-model";
documentModelAdministrationAsyncClient.getCopyAuthorization(modelId)
.subscribe(copyAuthorization ->
System.out.printf("Copy Authorization for model id: %s, access token: %s, expiration time: %s, "
+ "target resource ID; %s, target resource region: %s%n",
copyAuthorization.getTargetModelId(),
copyAuthorization.getAccessToken(),
copyAuthorization.getExpiresOn(),
copyAuthorization.getTargetResourceId(),
copyAuthorization.getTargetResourceRegion()
));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getCopyAuthorizationWithResponse() {
String modelId = "my-copied-model";
Map<String, String> attrs = new HashMap<String, String>();
attrs.put("createdBy", "sample");
documentModelAdministrationAsyncClient.getCopyAuthorizationWithResponse(modelId,
new CopyAuthorizationOptions()
.setDescription("model desc")
.setTags(attrs))
.subscribe(copyAuthorization ->
System.out.printf("Copy Authorization response status: %s, for model id: %s, access token: %s, "
+ "expiration time: %s, target resource ID; %s, target resource region: %s%n",
copyAuthorization.getStatusCode(),
copyAuthorization.getValue().getTargetModelId(),
copyAuthorization.getValue().getAccessToken(),
copyAuthorization.getValue().getExpiresOn(),
copyAuthorization.getValue().getTargetResourceId(),
copyAuthorization.getValue().getTargetResourceRegion()
));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getAccountProperties() {
documentModelAdministrationAsyncClient.getAccountProperties()
.subscribe(accountProperties -> {
System.out.printf("Max number of models that can be build for this account: %d%n",
accountProperties.getDocumentModelLimit());
System.out.printf("Current count of built document analysis models: %d%n",
accountProperties.getDocumentModelCount());
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getAccountPropertiesWithResponse() {
documentModelAdministrationAsyncClient.getAccountPropertiesWithResponse()
.subscribe(response -> {
System.out.printf("Response Status Code: %d.", response.getStatusCode());
AccountProperties accountProperties = response.getValue();
System.out.printf("Max number of models that can be build for this account: %d%n",
accountProperties.getDocumentModelLimit());
System.out.printf("Current count of built document analysis models: %d%n",
accountProperties.getDocumentModelCount());
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void beginCreateComposedModel() {
String modelId1 = "{model_Id_1}";
String modelId2 = "{model_Id_2}";
documentModelAdministrationAsyncClient.beginCreateComposedModel(Arrays.asList(modelId1, modelId2)
)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
* with options
*/
public void beginCreateComposedModelWithOptions() {
String modelId1 = "{model_Id_1}";
String modelId2 = "{model_Id_2}";
Map<String, String> attrs = new HashMap<String, String>();
attrs.put("createdBy", "sample");
documentModelAdministrationAsyncClient.beginCreateComposedModel(Arrays.asList(modelId1, modelId2),
new CreateComposedModelOptions().setDescription("model-desc").setTags(attrs))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Description: %s%n", documentModel.getDescription());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
System.out.printf("Model assigned tags: %s%n", documentModel.getTags());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void beginCopy() {
String copyModelId = "copy-model";
String targetModelId = "my-copied-model-id";
documentModelAdministrationAsyncClient.getCopyAuthorization(targetModelId)
.subscribe(copyAuthorization -> documentModelAdministrationAsyncClient.beginCopyModelTo(copyModelId,
copyAuthorization)
.filter(pollResponse -> pollResponse.getStatus().isComplete())
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel ->
System.out.printf("Copied model has model ID: %s, was created on: %s.%n,",
documentModel.getModelId(),
documentModel.getCreatedOn())));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void listModels() {
documentModelAdministrationAsyncClient.listModels()
.subscribe(documentModelInfo ->
System.out.printf("Model ID: %s, Model description: %s, Created on: %s.%n",
documentModelInfo.getModelId(),
documentModelInfo.getDescription(),
documentModelInfo.getCreatedOn()));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getModel() {
String modelId = "{model_id}";
documentModelAdministrationAsyncClient.getModel(modelId).subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Description: %s%n", documentModel.getDescription());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getModelWithResponse() {
String modelId = "{model_id}";
documentModelAdministrationAsyncClient.getModelWithResponse(modelId).subscribe(response -> {
System.out.printf("Response Status Code: %d.", response.getStatusCode());
DocumentModel documentModel = response.getValue();
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Description: %s%n", documentModel.getDescription());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getOperation() {
String operationId = "{operation_Id}";
documentModelAdministrationAsyncClient.getOperation(operationId).subscribe(modelOperation -> {
System.out.printf("Operation ID: %s%n", modelOperation.getOperationId());
System.out.printf("Operation Kind: %s%n", modelOperation.getKind());
System.out.printf("Operation Status: %s%n", modelOperation.getStatus());
System.out.printf("Model ID created with this operation: %s%n", modelOperation.getModelId());
if (ModelOperationStatus.FAILED.equals(modelOperation.getStatus())) {
System.out.printf("Operation fail error: %s%n", modelOperation.getError().getMessage());
}
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getOperationWithResponse() {
String operationId = "{operation_Id}";
documentModelAdministrationAsyncClient.getOperationWithResponse(operationId).subscribe(response -> {
System.out.printf("Response Status Code: %d.", response.getStatusCode());
ModelOperation modelOperation = response.getValue();
System.out.printf("Operation ID: %s%n", modelOperation.getOperationId());
System.out.printf("Operation Kind: %s%n", modelOperation.getKind());
System.out.printf("Operation Status: %s%n", modelOperation.getStatus());
System.out.printf("Model ID created with this operation: %s%n", modelOperation.getModelId());
if (ModelOperationStatus.FAILED.equals(modelOperation.getStatus())) {
System.out.printf("Operation fail error: %s%n", modelOperation.getError().getMessage());
}
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void listOperations() {
documentModelAdministrationAsyncClient.listOperations()
.subscribe(modelOperation -> {
System.out.printf("Operation ID: %s%n", modelOperation.getOperationId());
System.out.printf("Operation Status: %s%n", modelOperation.getStatus());
System.out.printf("Operation Created on: %s%n", modelOperation.getCreatedOn());
System.out.printf("Operation Percent completed: %d%n", modelOperation.getPercentCompleted());
System.out.printf("Operation Kind: %s%n", modelOperation.getKind());
System.out.printf("Operation Last updated on: %s%n", modelOperation.getLastUpdatedOn());
System.out.printf("Operation resource location: %s%n", modelOperation.getResourceLocation());
});
}
} | class DocumentModelAdminAsyncClientJavaDocCodeSnippets {
private final DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient =
new DocumentModelAdministrationClientBuilder().buildAsyncClient();
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient} initialization
*/
public void documentModelAdministrationAsyncClientInitialization() {
DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient =
new DocumentModelAdministrationClientBuilder().buildAsyncClient();
}
/**
* Code snippet for creating a {@link DocumentModelAdministrationAsyncClient} with pipeline
*/
public void createDocumentModelAdministrationAsyncClientWithPipeline() {
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(/* add policies */)
.build();
DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient =
new DocumentModelAdministrationClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.pipeline(pipeline)
.buildAsyncClient();
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
* with options
*/
public void beginBuildModelWithOptions() {
String trainingFilesUrl = "{SAS-URL-of-your-container-in-blob-storage}";
String modelId = "model-id";
Map<String, String> attrs = new HashMap<String, String>();
attrs.put("createdBy", "sample");
documentModelAdministrationAsyncClient.beginBuildModel(trainingFilesUrl,
DocumentBuildMode.TEMPLATE,
new BuildModelOptions()
.setModelId(modelId)
.setDescription("model desc")
.setPrefix("Invoice")
.setTags(attrs))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Description: %s%n", documentModel.getDescription());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
System.out.printf("Model assigned tags: %s%n", documentModel.getTags());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void deleteModel() {
String modelId = "{model_id}";
documentModelAdministrationAsyncClient.deleteModel(modelId)
.subscribe(ignored -> System.out.printf("Model ID: %s is deleted%n", modelId));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void deleteModelWithResponse() {
String modelId = "{model_id}";
documentModelAdministrationAsyncClient.deleteModelWithResponse(modelId)
.subscribe(response -> {
System.out.printf("Response Status Code: %d.", response.getStatusCode());
System.out.printf("Model ID: %s is deleted.%n", modelId);
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getCopyAuthorization() {
String modelId = "my-copied-model";
documentModelAdministrationAsyncClient.getCopyAuthorization()
.subscribe(copyAuthorization ->
System.out.printf("Copy Authorization for model id: %s, access token: %s, expiration time: %s, "
+ "target resource ID; %s, target resource region: %s%n",
copyAuthorization.getTargetModelId(),
copyAuthorization.getAccessToken(),
copyAuthorization.getExpiresOn(),
copyAuthorization.getTargetResourceId(),
copyAuthorization.getTargetResourceRegion()
));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getCopyAuthorizationWithResponse() {
String modelId = "my-copied-model";
Map<String, String> attrs = new HashMap<String, String>();
attrs.put("createdBy", "sample");
documentModelAdministrationAsyncClient.getCopyAuthorizationWithResponse(
new CopyAuthorizationOptions()
.setModelId(modelId)
.setDescription("model desc")
.setTags(attrs))
.subscribe(copyAuthorization ->
System.out.printf("Copy Authorization response status: %s, for model id: %s, access token: %s, "
+ "expiration time: %s, target resource ID; %s, target resource region: %s%n",
copyAuthorization.getStatusCode(),
copyAuthorization.getValue().getTargetModelId(),
copyAuthorization.getValue().getAccessToken(),
copyAuthorization.getValue().getExpiresOn(),
copyAuthorization.getValue().getTargetResourceId(),
copyAuthorization.getValue().getTargetResourceRegion()
));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getAccountProperties() {
documentModelAdministrationAsyncClient.getAccountProperties()
.subscribe(accountProperties -> {
System.out.printf("Max number of models that can be build for this account: %d%n",
accountProperties.getDocumentModelLimit());
System.out.printf("Current count of built document analysis models: %d%n",
accountProperties.getDocumentModelCount());
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getAccountPropertiesWithResponse() {
documentModelAdministrationAsyncClient.getAccountPropertiesWithResponse()
.subscribe(response -> {
System.out.printf("Response Status Code: %d.", response.getStatusCode());
AccountProperties accountProperties = response.getValue();
System.out.printf("Max number of models that can be build for this account: %d%n",
accountProperties.getDocumentModelLimit());
System.out.printf("Current count of built document analysis models: %d%n",
accountProperties.getDocumentModelCount());
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void beginCreateComposedModel() {
String modelId1 = "{model_Id_1}";
String modelId2 = "{model_Id_2}";
documentModelAdministrationAsyncClient.beginCreateComposedModel(Arrays.asList(modelId1, modelId2)
)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
* with options
*/
public void beginCreateComposedModelWithOptions() {
String modelId1 = "{model_Id_1}";
String modelId2 = "{model_Id_2}";
String modelId = "my-composed-model";
Map<String, String> attrs = new HashMap<String, String>();
attrs.put("createdBy", "sample");
documentModelAdministrationAsyncClient.beginCreateComposedModel(Arrays.asList(modelId1, modelId2),
new CreateComposedModelOptions()
.setModelId(modelId)
.setDescription("model-desc")
.setTags(attrs))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Description: %s%n", documentModel.getDescription());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
System.out.printf("Model assigned tags: %s%n", documentModel.getTags());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void beginCopy() {
String copyModelId = "copy-model";
documentModelAdministrationAsyncClient.getCopyAuthorization()
.subscribe(copyAuthorization -> documentModelAdministrationAsyncClient.beginCopyModelTo(copyModelId,
copyAuthorization)
.filter(pollResponse -> pollResponse.getStatus().isComplete())
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel ->
System.out.printf("Copied model has model ID: %s, was created on: %s.%n,",
documentModel.getModelId(),
documentModel.getCreatedOn())));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void listModels() {
documentModelAdministrationAsyncClient.listModels()
.subscribe(documentModelInfo ->
System.out.printf("Model ID: %s, Model description: %s, Created on: %s.%n",
documentModelInfo.getModelId(),
documentModelInfo.getDescription(),
documentModelInfo.getCreatedOn()));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getModel() {
String modelId = "{model_id}";
documentModelAdministrationAsyncClient.getModel(modelId).subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Description: %s%n", documentModel.getDescription());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getModelWithResponse() {
String modelId = "{model_id}";
documentModelAdministrationAsyncClient.getModelWithResponse(modelId).subscribe(response -> {
System.out.printf("Response Status Code: %d.", response.getStatusCode());
DocumentModel documentModel = response.getValue();
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Description: %s%n", documentModel.getDescription());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getOperation() {
String operationId = "{operation_Id}";
documentModelAdministrationAsyncClient.getOperation(operationId).subscribe(modelOperation -> {
System.out.printf("Operation ID: %s%n", modelOperation.getOperationId());
System.out.printf("Operation Kind: %s%n", modelOperation.getKind());
System.out.printf("Operation Status: %s%n", modelOperation.getStatus());
System.out.printf("Model ID created with this operation: %s%n", modelOperation.getModelId());
if (ModelOperationStatus.FAILED.equals(modelOperation.getStatus())) {
System.out.printf("Operation fail error: %s%n", modelOperation.getError().getMessage());
}
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getOperationWithResponse() {
String operationId = "{operation_Id}";
documentModelAdministrationAsyncClient.getOperationWithResponse(operationId).subscribe(response -> {
System.out.printf("Response Status Code: %d.", response.getStatusCode());
ModelOperation modelOperation = response.getValue();
System.out.printf("Operation ID: %s%n", modelOperation.getOperationId());
System.out.printf("Operation Kind: %s%n", modelOperation.getKind());
System.out.printf("Operation Status: %s%n", modelOperation.getStatus());
System.out.printf("Model ID created with this operation: %s%n", modelOperation.getModelId());
if (ModelOperationStatus.FAILED.equals(modelOperation.getStatus())) {
System.out.printf("Operation fail error: %s%n", modelOperation.getError().getMessage());
}
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void listOperations() {
documentModelAdministrationAsyncClient.listOperations()
.subscribe(modelOperation -> {
System.out.printf("Operation ID: %s%n", modelOperation.getOperationId());
System.out.printf("Operation Status: %s%n", modelOperation.getStatus());
System.out.printf("Operation Created on: %s%n", modelOperation.getCreatedOn());
System.out.printf("Operation Percent completed: %d%n", modelOperation.getPercentCompleted());
System.out.printf("Operation Kind: %s%n", modelOperation.getKind());
System.out.printf("Operation Last updated on: %s%n", modelOperation.getLastUpdatedOn());
System.out.printf("Operation resource location: %s%n", modelOperation.getResourceLocation());
});
}
} | |
Yeah, I've asked Jesse before about identifier validation, From client side, we don't have any validation. We just let service to validate the identifier. But I think the best practice is I should confirm what's the validation in service side. We could validate the identifier before we send them to service to reduce the cost. I chose to align with .NET SDK before, because I think we don't want to let users get two different behaviors in two language SDK. Overall, I'll confirm what's the validation in service side at least, and decide should we add validation in client and add to documentation. | EventHubAsyncClient buildAsyncClient() {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.boundedElastic();
}
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT;
}
final MessageSerializer messageSerializer = new EventHubMessageSerializer();
final EventHubConnectionProcessor processor;
if (isSharedConnection.get()) {
synchronized (connectionLock) {
if (eventHubConnectionProcessor == null) {
eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer);
}
}
processor = eventHubConnectionProcessor;
final int numberOfOpenClients = openClients.incrementAndGet();
LOGGER.info("
} else {
processor = buildConnectionProcessor(messageSerializer);
}
final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
String identifier;
if (clientOptions != null && clientOptions instanceof AmqpClientOptions) {
String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier();
identifier = clientOptionIdentifier == null ? UUID.randomUUID().toString() : clientOptionIdentifier;
} else {
identifier = UUID.randomUUID().toString();
}
return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler,
isSharedConnection.get(), this::onClientClose,
identifier);
} | } | EventHubAsyncClient buildAsyncClient() {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.boundedElastic();
}
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT;
}
final MessageSerializer messageSerializer = new EventHubMessageSerializer();
final EventHubConnectionProcessor processor;
if (isSharedConnection.get()) {
synchronized (connectionLock) {
if (eventHubConnectionProcessor == null) {
eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer);
}
}
processor = eventHubConnectionProcessor;
final int numberOfOpenClients = openClients.incrementAndGet();
LOGGER.info("
} else {
processor = buildConnectionProcessor(messageSerializer);
}
final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
String identifier;
if (clientOptions instanceof AmqpClientOptions) {
String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier();
identifier = CoreUtils.isNullOrEmpty(clientOptionIdentifier) ? UUID.randomUUID().toString() : clientOptionIdentifier;
} else {
identifier = UUID.randomUUID().toString();
}
return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler,
isSharedConnection.get(), this::onClientClose,
identifier);
} | class EventHubClientBuilder implements
TokenCredentialTrait<EventHubClientBuilder>,
AzureNamedKeyCredentialTrait<EventHubClientBuilder>,
ConnectionStringTrait<EventHubClientBuilder>,
AzureSasCredentialTrait<EventHubClientBuilder>,
AmqpTrait<EventHubClientBuilder>,
ConfigurationTrait<EventHubClientBuilder> {
static final int DEFAULT_PREFETCH_COUNT = 500;
static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1;
/**
* The name of the default consumer group in the Event Hubs service.
*/
public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default";
/**
* The minimum value allowed for the prefetch count of the consumer.
*/
private static final int MINIMUM_PREFETCH_COUNT = 1;
/**
* The maximum value allowed for the prefetch count of the consumer.
*/
private static final int MAXIMUM_PREFETCH_COUNT = 8000;
private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties";
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING";
private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions()
.setTryTimeout(ClientConstants.OPERATION_TIMEOUT);
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class);
private final Object connectionLock = new Object();
private final AtomicBoolean isSharedConnection = new AtomicBoolean();
private TokenCredential credentials;
private Configuration configuration;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport;
private String fullyQualifiedNamespace;
private String eventHubName;
private String consumerGroup;
private EventHubConnectionProcessor eventHubConnectionProcessor;
private Integer prefetchCount;
private ClientOptions clientOptions;
private SslDomain.VerifyMode verifyMode;
private URL customEndpointAddress;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
* non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer
* created using the builder.
*/
public EventHubClientBuilder() {
transport = AmqpTransportType.AMQP;
}
/**
* Sets the credential information given a connection string to the Event Hub instance.
*
* <p>
* If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the
* desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal
* "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub".
* </p>
*
* <p>
* If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string
* from that Event Hub will result in a connection string that contains the name.
* </p>
*
* @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected
* that the Event Hub name and the shared access key properties are contained in this connection string.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code
* connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
@Override
public EventHubClientBuilder connectionString(String connectionString) {
ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential);
}
private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
}
/**
* Sets the client options.
*
* @param clientOptions The client options.
* @return The updated {@link EventHubClientBuilder} object.
*/
@Override
public EventHubClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential information given a connection string to the Event Hubs namespace and name to a specific
* Event Hub instance.
*
* @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is
* expected that the shared access key properties are contained in this connection string, but not the Event Hub
* name.
* @param eventHubName The name of the Event Hub to connect the client to.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null.
* @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or,
* if the {@code connectionString} contains the Event Hub name.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString, String eventHubName) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (connectionString.isEmpty()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'connectionString' cannot be an empty string."));
} else if (eventHubName.isEmpty()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
if (!CoreUtils.isNullOrEmpty(properties.getEntityPath())
&& !eventHubName.equals(properties.getEntityPath())) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"'connectionString' contains an Event Hub name [%s] and it does not match the given "
+ "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. "
+ "Or supply a 'connectionString' without 'EntityPath' in it.",
properties.getEntityPath(), eventHubName)));
}
return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential);
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use
* {@link Configuration
*
* @param configuration The configuration store used to configure the {@link EventHubAsyncClient}.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
@Override
public EventHubClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network
* does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through
* an intermediary. For example: {@literal https:
* <p>
* If no port is specified, the default port for the {@link
* used.
*
* @param customEndpointAddress The custom endpoint address.
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}.
*/
public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) {
if (customEndpointAddress == null) {
this.customEndpointAddress = null;
return this;
}
try {
this.customEndpointAddress = new URL(customEndpointAddress);
} catch (MalformedURLException e) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e));
}
return this;
}
/**
* Sets the fully qualified name for the Event Hubs namespace.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string.
* @throws NullPointerException if {@code fullyQualifiedNamespace} is null.
*/
public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
private String getAndValidateFullyQualifiedNamespace() {
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return fullyQualifiedNamespace;
}
/**
* Sets the name of the Event Hub to connect the client to.
*
* @param eventHubName The name of the Event Hub to connect the client to.
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code eventHubName} is an empty string.
* @throws NullPointerException if {@code eventHubName} is null.
*/
public EventHubClientBuilder eventHubName(String eventHubName) {
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
return this;
}
private String getEventHubName() {
if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
return eventHubName;
}
/**
* Toggles the builder to use the same connection for producers or consumers that are built from this instance. By
* default, a new connection is constructed and used created for each Event Hub consumer or producer created.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder shareConnection() {
this.isSharedConnection.set(true);
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
* @param eventHubName The name of the Event Hub to connect the client to.
* @param credential The token credential to use for authorization. Access controls may be specified by the
* Event Hubs namespace or the requested Event Hub, depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty
* string.
* @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is
* null.
*/
public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName,
TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string."));
} else if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java
* <a href="https:
* documentation for more details on proper usage of the {@link TokenCredential} type.
*
* @param credential The token credential to use for authorization. Access controls may be specified by the
* Event Hubs namespace or the requested Event Hub, depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code credentials} is null.
*/
@Override
public EventHubClientBuilder credential(TokenCredential credential) {
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
* @param eventHubName The name of the Event Hub to connect the client to.
* @param credential The shared access name and key credential to use for authorization.
* Access controls may be specified by the Event Hubs namespace or the requested Event Hub,
* depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty
* string.
* @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is
* null.
*/
public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName,
AzureNamedKeyCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string."));
} else if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(),
credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY);
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param credential The shared access name and key credential to use for authorization.
* Access controls may be specified by the Event Hubs namespace or the requested Event Hub,
* depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code credentials} is null.
*/
@Override
public EventHubClientBuilder credential(AzureNamedKeyCredential credential) {
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(),
credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY);
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
* @param eventHubName The name of the Event Hub to connect the client to.
* @param credential The shared access signature credential to use for authorization.
* Access controls may be specified by the Event Hubs namespace or the requested Event Hub,
* depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty
* string.
* @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is
* null.
*/
public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName,
AzureSasCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string."));
} else if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new EventHubSharedKeyCredential(credential.getSignature());
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param credential The shared access signature credential to use for authorization.
* Access controls may be specified by the Event Hubs namespace or the requested Event Hub,
* depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code credentials} is null.
*/
@Override
public EventHubClientBuilder credential(AzureSasCredential credential) {
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new EventHubSharedKeyCredential(credential.getSignature());
return this;
}
/**
* Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
@Override
public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link
* AmqpTransportType
*
* @param transport The transport type to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
@Override
public EventHubClientBuilder transportType(AmqpTransportType transport) {
this.transport = transport;
return this;
}
/**
* Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used.
*
* @param retryOptions The retry policy to use.
*
* @return The updated {@link EventHubClientBuilder} object.
* @deprecated Replaced by {@link
*/
@Deprecated
public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used.
*
* @param retryOptions The retry policy to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
@Override
public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the name of the consumer group this consumer is associated with. Events are read in the context of this
* group. The name of the consumer group that is created by default is {@link
* "$Default"}.
*
* @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the
* context of this group. The name of the consumer group that is created by default is {@link
*
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder consumerGroup(String consumerGroup) {
this.consumerGroup = consumerGroup;
return this;
}
/**
* Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive
* and queue locally without regard to whether a receive operation is currently active.
*
* @param prefetchCount The amount of events to queue locally.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code prefetchCount} is less than {@link
* greater than {@link
*/
public EventHubClientBuilder prefetchCount(int prefetchCount) {
if (prefetchCount < MINIMUM_PREFETCH_COUNT) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT)));
}
if (prefetchCount > MAXIMUM_PREFETCH_COUNT) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT)));
}
this.prefetchCount = prefetchCount;
return this;
}
/**
* Package-private method that gets the prefetch count.
*
* @return Gets the prefetch count or {@code null} if it has not been set.
* @see
*/
Integer getPrefetchCount() {
return prefetchCount;
}
/**
* Package-private method that sets the scheduler for the created Event Hub client.
*
* @param scheduler Scheduler to set.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Package-private method that sets the verify mode for this connection.
*
* @param verifyMode The verification mode.
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) {
this.verifyMode = verifyMode;
return this;
}
/**
* Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code
* buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created.
*
* @return A new {@link EventHubConsumerAsyncClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerAsyncClient buildAsyncConsumerClient() {
if (CoreUtils.isNullOrEmpty(consumerGroup)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty "
+ "string. using EventHubClientBuilder.consumerGroup(String)"));
}
return buildAsyncClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code
* buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created.
*
* @return A new {@link EventHubConsumerClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerClient buildConsumerClient() {
return buildClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created.
*
* @return A new {@link EventHubProducerAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerAsyncClient buildAsyncProducerClient() {
return buildAsyncClient().createProducer();
}
/**
* Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created.
*
* @return A new {@link EventHubProducerClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerClient buildProducerClient() {
return buildClient().createProducer();
}
/**
* Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* </ul>
*
* @return A new {@link EventHubAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
/**
* Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is
* invoked, a new instance of {@link EventHubClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubClient buildClient() {
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT;
}
final EventHubAsyncClient client = buildAsyncClient();
return new EventHubClient(client, retryOptions);
}
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
LOGGER.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
LOGGER.info("No more open clients, closing shared connection.");
if (eventHubConnectionProcessor != null) {
eventHubConnectionProcessor.dispose();
eventHubConnectionProcessor = null;
} else {
LOGGER.warning("Shared EventHubConnectionProcessor was already disposed.");
}
}
}
private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> {
sink.onRequest(request -> {
if (request == 0) {
return;
} else if (request > 1) {
sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException(
"Requested more than one connection. Only emitting one. Request: " + request)));
return;
}
final String connectionId = StringUtil.getRandomString("MF");
LOGGER.atInfo()
.addKeyValue(CONNECTION_ID_KEY, connectionId)
.log("Emitting a single connection.");
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
connectionOptions.getAuthorizationScope());
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId,
connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider,
messageSerializer);
sink.next(connection);
});
});
return connectionFlux.subscribeWith(new EventHubConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry()));
}
private ConnectionOptions getConnectionOptions() {
Configuration buildConfiguration = configuration == null
? Configuration.getGlobalConfiguration().clone()
: configuration;
if (credentials == null) {
final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING);
if (CoreUtils.isNullOrEmpty(connectionString)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "credentials(String, String, TokenCredential), or setting the environment variable '"
+ AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string"));
}
connectionString(connectionString);
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(buildConfiguration);
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP Web Sockets."));
}
final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
final SslDomain.VerifyMode verificationMode = verifyMode != null
? verifyMode
: SslDomain.VerifyMode.VERIFY_PEER_NAME;
final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions();
final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
if (customEndpointAddress == null) {
return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType,
ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler,
options, verificationMode, product, clientVersion);
} else {
return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType,
ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler,
options, verificationMode, product, clientVersion, customEndpointAddress.getHost(),
customEndpointAddress.getPort());
}
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress, configuration,
Boolean.parseBoolean(configuration.get("java.net.useSystemProxies")));
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress,
Configuration configuration, boolean useSystemProxies) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else if (useSystemProxies) {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
Proxy.Type proxyType = coreProxyOptions.getType().toProxyType();
InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress();
String username = coreProxyOptions.getUsername();
String password = coreProxyOptions.getPassword();
return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password);
} else {
LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't "
+ "set or was false.");
return ProxyOptions.SYSTEM_DEFAULTS;
}
}
} | class EventHubClientBuilder implements
TokenCredentialTrait<EventHubClientBuilder>,
AzureNamedKeyCredentialTrait<EventHubClientBuilder>,
ConnectionStringTrait<EventHubClientBuilder>,
AzureSasCredentialTrait<EventHubClientBuilder>,
AmqpTrait<EventHubClientBuilder>,
ConfigurationTrait<EventHubClientBuilder> {
static final int DEFAULT_PREFETCH_COUNT = 500;
static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1;
/**
* The name of the default consumer group in the Event Hubs service.
*/
public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default";
/**
* The minimum value allowed for the prefetch count of the consumer.
*/
private static final int MINIMUM_PREFETCH_COUNT = 1;
/**
* The maximum value allowed for the prefetch count of the consumer.
*/
private static final int MAXIMUM_PREFETCH_COUNT = 8000;
private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties";
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING";
private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions()
.setTryTimeout(ClientConstants.OPERATION_TIMEOUT);
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class);
private final Object connectionLock = new Object();
private final AtomicBoolean isSharedConnection = new AtomicBoolean();
private TokenCredential credentials;
private Configuration configuration;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport;
private String fullyQualifiedNamespace;
private String eventHubName;
private String consumerGroup;
private EventHubConnectionProcessor eventHubConnectionProcessor;
private Integer prefetchCount;
private ClientOptions clientOptions;
private SslDomain.VerifyMode verifyMode;
private URL customEndpointAddress;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
* non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer
* created using the builder.
*/
public EventHubClientBuilder() {
transport = AmqpTransportType.AMQP;
}
/**
* Sets the credential information given a connection string to the Event Hub instance.
*
* <p>
* If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the
* desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal
* "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub".
* </p>
*
* <p>
* If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string
* from that Event Hub will result in a connection string that contains the name.
* </p>
*
* @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected
* that the Event Hub name and the shared access key properties are contained in this connection string.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code
* connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
@Override
public EventHubClientBuilder connectionString(String connectionString) {
ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential);
}
private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
}
/**
* Sets the client options.
*
* @param clientOptions The client options.
* @return The updated {@link EventHubClientBuilder} object.
*/
@Override
public EventHubClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential information given a connection string to the Event Hubs namespace and name to a specific
* Event Hub instance.
*
* @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is
* expected that the shared access key properties are contained in this connection string, but not the Event Hub
* name.
* @param eventHubName The name of the Event Hub to connect the client to.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null.
* @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or,
* if the {@code connectionString} contains the Event Hub name.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString, String eventHubName) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (connectionString.isEmpty()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'connectionString' cannot be an empty string."));
} else if (eventHubName.isEmpty()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
if (!CoreUtils.isNullOrEmpty(properties.getEntityPath())
&& !eventHubName.equals(properties.getEntityPath())) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"'connectionString' contains an Event Hub name [%s] and it does not match the given "
+ "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. "
+ "Or supply a 'connectionString' without 'EntityPath' in it.",
properties.getEntityPath(), eventHubName)));
}
return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential);
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use
* {@link Configuration
*
* @param configuration The configuration store used to configure the {@link EventHubAsyncClient}.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
@Override
public EventHubClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network
* does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through
* an intermediary. For example: {@literal https:
* <p>
* If no port is specified, the default port for the {@link
* used.
*
* @param customEndpointAddress The custom endpoint address.
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}.
*/
public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) {
if (customEndpointAddress == null) {
this.customEndpointAddress = null;
return this;
}
try {
this.customEndpointAddress = new URL(customEndpointAddress);
} catch (MalformedURLException e) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e));
}
return this;
}
/**
* Sets the fully qualified name for the Event Hubs namespace.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string.
* @throws NullPointerException if {@code fullyQualifiedNamespace} is null.
*/
public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
private String getAndValidateFullyQualifiedNamespace() {
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return fullyQualifiedNamespace;
}
/**
* Sets the name of the Event Hub to connect the client to.
*
* @param eventHubName The name of the Event Hub to connect the client to.
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code eventHubName} is an empty string.
* @throws NullPointerException if {@code eventHubName} is null.
*/
public EventHubClientBuilder eventHubName(String eventHubName) {
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
return this;
}
private String getEventHubName() {
if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
return eventHubName;
}
/**
* Toggles the builder to use the same connection for producers or consumers that are built from this instance. By
* default, a new connection is constructed and used created for each Event Hub consumer or producer created.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder shareConnection() {
this.isSharedConnection.set(true);
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
* @param eventHubName The name of the Event Hub to connect the client to.
* @param credential The token credential to use for authorization. Access controls may be specified by the
* Event Hubs namespace or the requested Event Hub, depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty
* string.
* @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is
* null.
*/
public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName,
TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string."));
} else if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java
* <a href="https:
* documentation for more details on proper usage of the {@link TokenCredential} type.
*
* @param credential The token credential to use for authorization. Access controls may be specified by the
* Event Hubs namespace or the requested Event Hub, depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code credentials} is null.
*/
@Override
public EventHubClientBuilder credential(TokenCredential credential) {
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
* @param eventHubName The name of the Event Hub to connect the client to.
* @param credential The shared access name and key credential to use for authorization.
* Access controls may be specified by the Event Hubs namespace or the requested Event Hub,
* depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty
* string.
* @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is
* null.
*/
public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName,
AzureNamedKeyCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string."));
} else if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(),
credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY);
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param credential The shared access name and key credential to use for authorization.
* Access controls may be specified by the Event Hubs namespace or the requested Event Hub,
* depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code credentials} is null.
*/
@Override
public EventHubClientBuilder credential(AzureNamedKeyCredential credential) {
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(),
credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY);
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
* @param eventHubName The name of the Event Hub to connect the client to.
* @param credential The shared access signature credential to use for authorization.
* Access controls may be specified by the Event Hubs namespace or the requested Event Hub,
* depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty
* string.
* @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is
* null.
*/
public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName,
AzureSasCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string."));
} else if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new EventHubSharedKeyCredential(credential.getSignature());
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param credential The shared access signature credential to use for authorization.
* Access controls may be specified by the Event Hubs namespace or the requested Event Hub,
* depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code credentials} is null.
*/
@Override
public EventHubClientBuilder credential(AzureSasCredential credential) {
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new EventHubSharedKeyCredential(credential.getSignature());
return this;
}
/**
* Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
@Override
public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link
* AmqpTransportType
*
* @param transport The transport type to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
@Override
public EventHubClientBuilder transportType(AmqpTransportType transport) {
this.transport = transport;
return this;
}
/**
* Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used.
*
* @param retryOptions The retry policy to use.
*
* @return The updated {@link EventHubClientBuilder} object.
* @deprecated Replaced by {@link
*/
@Deprecated
public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used.
*
* @param retryOptions The retry policy to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
@Override
public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the name of the consumer group this consumer is associated with. Events are read in the context of this
* group. The name of the consumer group that is created by default is {@link
* "$Default"}.
*
* @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the
* context of this group. The name of the consumer group that is created by default is {@link
*
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder consumerGroup(String consumerGroup) {
this.consumerGroup = consumerGroup;
return this;
}
/**
* Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive
* and queue locally without regard to whether a receive operation is currently active.
*
* @param prefetchCount The amount of events to queue locally.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code prefetchCount} is less than {@link
* greater than {@link
*/
public EventHubClientBuilder prefetchCount(int prefetchCount) {
if (prefetchCount < MINIMUM_PREFETCH_COUNT) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT)));
}
if (prefetchCount > MAXIMUM_PREFETCH_COUNT) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT)));
}
this.prefetchCount = prefetchCount;
return this;
}
/**
* Package-private method that gets the prefetch count.
*
* @return Gets the prefetch count or {@code null} if it has not been set.
* @see
*/
Integer getPrefetchCount() {
return prefetchCount;
}
/**
* Package-private method that sets the scheduler for the created Event Hub client.
*
* @param scheduler Scheduler to set.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Package-private method that sets the verify mode for this connection.
*
* @param verifyMode The verification mode.
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) {
this.verifyMode = verifyMode;
return this;
}
/**
* Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code
* buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created.
*
* @return A new {@link EventHubConsumerAsyncClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerAsyncClient buildAsyncConsumerClient() {
if (CoreUtils.isNullOrEmpty(consumerGroup)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty "
+ "string. using EventHubClientBuilder.consumerGroup(String)"));
}
return buildAsyncClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code
* buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created.
*
* @return A new {@link EventHubConsumerClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerClient buildConsumerClient() {
return buildClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created.
*
* @return A new {@link EventHubProducerAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerAsyncClient buildAsyncProducerClient() {
return buildAsyncClient().createProducer();
}
/**
* Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created.
*
* @return A new {@link EventHubProducerClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerClient buildProducerClient() {
return buildClient().createProducer();
}
/**
* Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* </ul>
*
* @return A new {@link EventHubAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
/**
* Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is
* invoked, a new instance of {@link EventHubClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubClient buildClient() {
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT;
}
final EventHubAsyncClient client = buildAsyncClient();
return new EventHubClient(client, retryOptions);
}
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
LOGGER.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
LOGGER.info("No more open clients, closing shared connection.");
if (eventHubConnectionProcessor != null) {
eventHubConnectionProcessor.dispose();
eventHubConnectionProcessor = null;
} else {
LOGGER.warning("Shared EventHubConnectionProcessor was already disposed.");
}
}
}
private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> {
sink.onRequest(request -> {
if (request == 0) {
return;
} else if (request > 1) {
sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException(
"Requested more than one connection. Only emitting one. Request: " + request)));
return;
}
final String connectionId = StringUtil.getRandomString("MF");
LOGGER.atInfo()
.addKeyValue(CONNECTION_ID_KEY, connectionId)
.log("Emitting a single connection.");
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
connectionOptions.getAuthorizationScope());
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId,
connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider,
messageSerializer);
sink.next(connection);
});
});
return connectionFlux.subscribeWith(new EventHubConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry()));
}
private ConnectionOptions getConnectionOptions() {
Configuration buildConfiguration = configuration == null
? Configuration.getGlobalConfiguration().clone()
: configuration;
if (credentials == null) {
final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING);
if (CoreUtils.isNullOrEmpty(connectionString)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "credentials(String, String, TokenCredential), or setting the environment variable '"
+ AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string"));
}
connectionString(connectionString);
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(buildConfiguration);
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP Web Sockets."));
}
final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
final SslDomain.VerifyMode verificationMode = verifyMode != null
? verifyMode
: SslDomain.VerifyMode.VERIFY_PEER_NAME;
final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions();
final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
if (customEndpointAddress == null) {
return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType,
ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler,
options, verificationMode, product, clientVersion);
} else {
return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType,
ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler,
options, verificationMode, product, clientVersion, customEndpointAddress.getHost(),
customEndpointAddress.getPort());
}
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress, configuration,
Boolean.parseBoolean(configuration.get("java.net.useSystemProxies")));
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress,
Configuration configuration, boolean useSystemProxies) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else if (useSystemProxies) {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
Proxy.Type proxyType = coreProxyOptions.getType().toProxyType();
InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress();
String username = coreProxyOptions.getUsername();
String password = coreProxyOptions.getPassword();
return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password);
} else {
LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't "
+ "set or was false.");
return ProxyOptions.SYSTEM_DEFAULTS;
}
}
} |
yes, I think it was missing from the codesnippet tag, but was included in the examples, so it still showed up on the code examples. Just corrected this. | public void beginBuildModel() {
String trainingFilesUrl = "{SAS-URL-of-your-container-in-blob-storage}";
documentModelAdministrationAsyncClient.beginBuildModel(trainingFilesUrl, DocumentBuildMode.TEMPLATE
)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
} | public void beginBuildModel() {
String trainingFilesUrl = "{SAS-URL-of-your-container-in-blob-storage}";
documentModelAdministrationAsyncClient.beginBuildModel(trainingFilesUrl, DocumentBuildMode.TEMPLATE
)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
} | class DocumentModelAdminAsyncClientJavaDocCodeSnippets {
private final DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient =
new DocumentModelAdministrationClientBuilder().buildAsyncClient();
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient} initialization
*/
public void formTrainingAsyncClientInInitialization() {
DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient =
new DocumentModelAdministrationClientBuilder().buildAsyncClient();
}
/**
* Code snippet for creating a {@link DocumentModelAdministrationAsyncClient} with pipeline
*/
public void createDocumentTrainingAsyncClientWithPipeline() {
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(/* add policies */)
.build();
DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient =
new DocumentModelAdministrationClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.pipeline(pipeline)
.buildAsyncClient();
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
* with options
*/
public void beginBuildModelWithOptions() {
String trainingFilesUrl = "{SAS-URL-of-your-container-in-blob-storage}";
Map<String, String> attrs = new HashMap<String, String>();
attrs.put("createdBy", "sample");
documentModelAdministrationAsyncClient.beginBuildModel(trainingFilesUrl,
DocumentBuildMode.TEMPLATE,
new BuildModelOptions()
.setDescription("model desc")
.setPrefix("Invoice")
.setTags(attrs))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Description: %s%n", documentModel.getDescription());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
System.out.printf("Model assigned tags: %s%n", documentModel.getTags());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void deleteModel() {
String modelId = "{model_id}";
documentModelAdministrationAsyncClient.deleteModel(modelId)
.subscribe(ignored -> System.out.printf("Model ID: %s is deleted%n", modelId));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void deleteModelWithResponse() {
String modelId = "{model_id}";
documentModelAdministrationAsyncClient.deleteModelWithResponse(modelId)
.subscribe(response -> {
System.out.printf("Response Status Code: %d.", response.getStatusCode());
System.out.printf("Model ID: %s is deleted.%n", modelId);
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getCopyAuthorization() {
String modelId = "my-copied-model";
documentModelAdministrationAsyncClient.getCopyAuthorization(modelId)
.subscribe(copyAuthorization ->
System.out.printf("Copy Authorization for model id: %s, access token: %s, expiration time: %s, "
+ "target resource ID; %s, target resource region: %s%n",
copyAuthorization.getTargetModelId(),
copyAuthorization.getAccessToken(),
copyAuthorization.getExpiresOn(),
copyAuthorization.getTargetResourceId(),
copyAuthorization.getTargetResourceRegion()
));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getCopyAuthorizationWithResponse() {
String modelId = "my-copied-model";
Map<String, String> attrs = new HashMap<String, String>();
attrs.put("createdBy", "sample");
documentModelAdministrationAsyncClient.getCopyAuthorizationWithResponse(modelId,
new CopyAuthorizationOptions()
.setDescription("model desc")
.setTags(attrs))
.subscribe(copyAuthorization ->
System.out.printf("Copy Authorization response status: %s, for model id: %s, access token: %s, "
+ "expiration time: %s, target resource ID; %s, target resource region: %s%n",
copyAuthorization.getStatusCode(),
copyAuthorization.getValue().getTargetModelId(),
copyAuthorization.getValue().getAccessToken(),
copyAuthorization.getValue().getExpiresOn(),
copyAuthorization.getValue().getTargetResourceId(),
copyAuthorization.getValue().getTargetResourceRegion()
));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getAccountProperties() {
documentModelAdministrationAsyncClient.getAccountProperties()
.subscribe(accountProperties -> {
System.out.printf("Max number of models that can be build for this account: %d%n",
accountProperties.getDocumentModelLimit());
System.out.printf("Current count of built document analysis models: %d%n",
accountProperties.getDocumentModelCount());
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getAccountPropertiesWithResponse() {
documentModelAdministrationAsyncClient.getAccountPropertiesWithResponse()
.subscribe(response -> {
System.out.printf("Response Status Code: %d.", response.getStatusCode());
AccountProperties accountProperties = response.getValue();
System.out.printf("Max number of models that can be build for this account: %d%n",
accountProperties.getDocumentModelLimit());
System.out.printf("Current count of built document analysis models: %d%n",
accountProperties.getDocumentModelCount());
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void beginCreateComposedModel() {
String modelId1 = "{model_Id_1}";
String modelId2 = "{model_Id_2}";
documentModelAdministrationAsyncClient.beginCreateComposedModel(Arrays.asList(modelId1, modelId2)
)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
* with options
*/
public void beginCreateComposedModelWithOptions() {
String modelId1 = "{model_Id_1}";
String modelId2 = "{model_Id_2}";
Map<String, String> attrs = new HashMap<String, String>();
attrs.put("createdBy", "sample");
documentModelAdministrationAsyncClient.beginCreateComposedModel(Arrays.asList(modelId1, modelId2),
new CreateComposedModelOptions().setDescription("model-desc").setTags(attrs))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Description: %s%n", documentModel.getDescription());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
System.out.printf("Model assigned tags: %s%n", documentModel.getTags());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void beginCopy() {
String copyModelId = "copy-model";
String targetModelId = "my-copied-model-id";
documentModelAdministrationAsyncClient.getCopyAuthorization(targetModelId)
.subscribe(copyAuthorization -> documentModelAdministrationAsyncClient.beginCopyModelTo(copyModelId,
copyAuthorization)
.filter(pollResponse -> pollResponse.getStatus().isComplete())
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel ->
System.out.printf("Copied model has model ID: %s, was created on: %s.%n,",
documentModel.getModelId(),
documentModel.getCreatedOn())));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void listModels() {
documentModelAdministrationAsyncClient.listModels()
.subscribe(documentModelInfo ->
System.out.printf("Model ID: %s, Model description: %s, Created on: %s.%n",
documentModelInfo.getModelId(),
documentModelInfo.getDescription(),
documentModelInfo.getCreatedOn()));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getModel() {
String modelId = "{model_id}";
documentModelAdministrationAsyncClient.getModel(modelId).subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Description: %s%n", documentModel.getDescription());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getModelWithResponse() {
String modelId = "{model_id}";
documentModelAdministrationAsyncClient.getModelWithResponse(modelId).subscribe(response -> {
System.out.printf("Response Status Code: %d.", response.getStatusCode());
DocumentModel documentModel = response.getValue();
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Description: %s%n", documentModel.getDescription());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getOperation() {
String operationId = "{operation_Id}";
documentModelAdministrationAsyncClient.getOperation(operationId).subscribe(modelOperation -> {
System.out.printf("Operation ID: %s%n", modelOperation.getOperationId());
System.out.printf("Operation Kind: %s%n", modelOperation.getKind());
System.out.printf("Operation Status: %s%n", modelOperation.getStatus());
System.out.printf("Model ID created with this operation: %s%n", modelOperation.getModelId());
if (ModelOperationStatus.FAILED.equals(modelOperation.getStatus())) {
System.out.printf("Operation fail error: %s%n", modelOperation.getError().getMessage());
}
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getOperationWithResponse() {
String operationId = "{operation_Id}";
documentModelAdministrationAsyncClient.getOperationWithResponse(operationId).subscribe(response -> {
System.out.printf("Response Status Code: %d.", response.getStatusCode());
ModelOperation modelOperation = response.getValue();
System.out.printf("Operation ID: %s%n", modelOperation.getOperationId());
System.out.printf("Operation Kind: %s%n", modelOperation.getKind());
System.out.printf("Operation Status: %s%n", modelOperation.getStatus());
System.out.printf("Model ID created with this operation: %s%n", modelOperation.getModelId());
if (ModelOperationStatus.FAILED.equals(modelOperation.getStatus())) {
System.out.printf("Operation fail error: %s%n", modelOperation.getError().getMessage());
}
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void listOperations() {
documentModelAdministrationAsyncClient.listOperations()
.subscribe(modelOperation -> {
System.out.printf("Operation ID: %s%n", modelOperation.getOperationId());
System.out.printf("Operation Status: %s%n", modelOperation.getStatus());
System.out.printf("Operation Created on: %s%n", modelOperation.getCreatedOn());
System.out.printf("Operation Percent completed: %d%n", modelOperation.getPercentCompleted());
System.out.printf("Operation Kind: %s%n", modelOperation.getKind());
System.out.printf("Operation Last updated on: %s%n", modelOperation.getLastUpdatedOn());
System.out.printf("Operation resource location: %s%n", modelOperation.getResourceLocation());
});
}
} | class DocumentModelAdminAsyncClientJavaDocCodeSnippets {
private final DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient =
new DocumentModelAdministrationClientBuilder().buildAsyncClient();
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient} initialization
*/
public void documentModelAdministrationAsyncClientInitialization() {
DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient =
new DocumentModelAdministrationClientBuilder().buildAsyncClient();
}
/**
* Code snippet for creating a {@link DocumentModelAdministrationAsyncClient} with pipeline
*/
public void createDocumentModelAdministrationAsyncClientWithPipeline() {
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(/* add policies */)
.build();
DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient =
new DocumentModelAdministrationClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.pipeline(pipeline)
.buildAsyncClient();
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
* with options
*/
public void beginBuildModelWithOptions() {
String trainingFilesUrl = "{SAS-URL-of-your-container-in-blob-storage}";
String modelId = "model-id";
Map<String, String> attrs = new HashMap<String, String>();
attrs.put("createdBy", "sample");
documentModelAdministrationAsyncClient.beginBuildModel(trainingFilesUrl,
DocumentBuildMode.TEMPLATE,
new BuildModelOptions()
.setModelId(modelId)
.setDescription("model desc")
.setPrefix("Invoice")
.setTags(attrs))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Description: %s%n", documentModel.getDescription());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
System.out.printf("Model assigned tags: %s%n", documentModel.getTags());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void deleteModel() {
String modelId = "{model_id}";
documentModelAdministrationAsyncClient.deleteModel(modelId)
.subscribe(ignored -> System.out.printf("Model ID: %s is deleted%n", modelId));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void deleteModelWithResponse() {
String modelId = "{model_id}";
documentModelAdministrationAsyncClient.deleteModelWithResponse(modelId)
.subscribe(response -> {
System.out.printf("Response Status Code: %d.", response.getStatusCode());
System.out.printf("Model ID: %s is deleted.%n", modelId);
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getCopyAuthorization() {
String modelId = "my-copied-model";
documentModelAdministrationAsyncClient.getCopyAuthorization()
.subscribe(copyAuthorization ->
System.out.printf("Copy Authorization for model id: %s, access token: %s, expiration time: %s, "
+ "target resource ID; %s, target resource region: %s%n",
copyAuthorization.getTargetModelId(),
copyAuthorization.getAccessToken(),
copyAuthorization.getExpiresOn(),
copyAuthorization.getTargetResourceId(),
copyAuthorization.getTargetResourceRegion()
));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getCopyAuthorizationWithResponse() {
String modelId = "my-copied-model";
Map<String, String> attrs = new HashMap<String, String>();
attrs.put("createdBy", "sample");
documentModelAdministrationAsyncClient.getCopyAuthorizationWithResponse(
new CopyAuthorizationOptions()
.setModelId(modelId)
.setDescription("model desc")
.setTags(attrs))
.subscribe(copyAuthorization ->
System.out.printf("Copy Authorization response status: %s, for model id: %s, access token: %s, "
+ "expiration time: %s, target resource ID; %s, target resource region: %s%n",
copyAuthorization.getStatusCode(),
copyAuthorization.getValue().getTargetModelId(),
copyAuthorization.getValue().getAccessToken(),
copyAuthorization.getValue().getExpiresOn(),
copyAuthorization.getValue().getTargetResourceId(),
copyAuthorization.getValue().getTargetResourceRegion()
));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getAccountProperties() {
documentModelAdministrationAsyncClient.getAccountProperties()
.subscribe(accountProperties -> {
System.out.printf("Max number of models that can be build for this account: %d%n",
accountProperties.getDocumentModelLimit());
System.out.printf("Current count of built document analysis models: %d%n",
accountProperties.getDocumentModelCount());
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getAccountPropertiesWithResponse() {
documentModelAdministrationAsyncClient.getAccountPropertiesWithResponse()
.subscribe(response -> {
System.out.printf("Response Status Code: %d.", response.getStatusCode());
AccountProperties accountProperties = response.getValue();
System.out.printf("Max number of models that can be build for this account: %d%n",
accountProperties.getDocumentModelLimit());
System.out.printf("Current count of built document analysis models: %d%n",
accountProperties.getDocumentModelCount());
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void beginCreateComposedModel() {
String modelId1 = "{model_Id_1}";
String modelId2 = "{model_Id_2}";
documentModelAdministrationAsyncClient.beginCreateComposedModel(Arrays.asList(modelId1, modelId2)
)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
* with options
*/
public void beginCreateComposedModelWithOptions() {
String modelId1 = "{model_Id_1}";
String modelId2 = "{model_Id_2}";
String modelId = "my-composed-model";
Map<String, String> attrs = new HashMap<String, String>();
attrs.put("createdBy", "sample");
documentModelAdministrationAsyncClient.beginCreateComposedModel(Arrays.asList(modelId1, modelId2),
new CreateComposedModelOptions()
.setModelId(modelId)
.setDescription("model-desc")
.setTags(attrs))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Description: %s%n", documentModel.getDescription());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
System.out.printf("Model assigned tags: %s%n", documentModel.getTags());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void beginCopy() {
String copyModelId = "copy-model";
documentModelAdministrationAsyncClient.getCopyAuthorization()
.subscribe(copyAuthorization -> documentModelAdministrationAsyncClient.beginCopyModelTo(copyModelId,
copyAuthorization)
.filter(pollResponse -> pollResponse.getStatus().isComplete())
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(documentModel ->
System.out.printf("Copied model has model ID: %s, was created on: %s.%n,",
documentModel.getModelId(),
documentModel.getCreatedOn())));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void listModels() {
documentModelAdministrationAsyncClient.listModels()
.subscribe(documentModelInfo ->
System.out.printf("Model ID: %s, Model description: %s, Created on: %s.%n",
documentModelInfo.getModelId(),
documentModelInfo.getDescription(),
documentModelInfo.getCreatedOn()));
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getModel() {
String modelId = "{model_id}";
documentModelAdministrationAsyncClient.getModel(modelId).subscribe(documentModel -> {
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Description: %s%n", documentModel.getDescription());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getModelWithResponse() {
String modelId = "{model_id}";
documentModelAdministrationAsyncClient.getModelWithResponse(modelId).subscribe(response -> {
System.out.printf("Response Status Code: %d.", response.getStatusCode());
DocumentModel documentModel = response.getValue();
System.out.printf("Model ID: %s%n", documentModel.getModelId());
System.out.printf("Model Description: %s%n", documentModel.getDescription());
System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn());
documentModel.getDocTypes().forEach((key, docTypeInfo) -> {
docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> {
System.out.printf("Field: %s", field);
System.out.printf("Field type: %s", documentFieldSchema.getType());
System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field));
});
});
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getOperation() {
String operationId = "{operation_Id}";
documentModelAdministrationAsyncClient.getOperation(operationId).subscribe(modelOperation -> {
System.out.printf("Operation ID: %s%n", modelOperation.getOperationId());
System.out.printf("Operation Kind: %s%n", modelOperation.getKind());
System.out.printf("Operation Status: %s%n", modelOperation.getStatus());
System.out.printf("Model ID created with this operation: %s%n", modelOperation.getModelId());
if (ModelOperationStatus.FAILED.equals(modelOperation.getStatus())) {
System.out.printf("Operation fail error: %s%n", modelOperation.getError().getMessage());
}
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void getOperationWithResponse() {
String operationId = "{operation_Id}";
documentModelAdministrationAsyncClient.getOperationWithResponse(operationId).subscribe(response -> {
System.out.printf("Response Status Code: %d.", response.getStatusCode());
ModelOperation modelOperation = response.getValue();
System.out.printf("Operation ID: %s%n", modelOperation.getOperationId());
System.out.printf("Operation Kind: %s%n", modelOperation.getKind());
System.out.printf("Operation Status: %s%n", modelOperation.getStatus());
System.out.printf("Model ID created with this operation: %s%n", modelOperation.getModelId());
if (ModelOperationStatus.FAILED.equals(modelOperation.getStatus())) {
System.out.printf("Operation fail error: %s%n", modelOperation.getError().getMessage());
}
});
}
/**
* Code snippet for {@link DocumentModelAdministrationAsyncClient
*/
public void listOperations() {
documentModelAdministrationAsyncClient.listOperations()
.subscribe(modelOperation -> {
System.out.printf("Operation ID: %s%n", modelOperation.getOperationId());
System.out.printf("Operation Status: %s%n", modelOperation.getStatus());
System.out.printf("Operation Created on: %s%n", modelOperation.getCreatedOn());
System.out.printf("Operation Percent completed: %d%n", modelOperation.getPercentCompleted());
System.out.printf("Operation Kind: %s%n", modelOperation.getKind());
System.out.printf("Operation Last updated on: %s%n", modelOperation.getLastUpdatedOn());
System.out.printf("Operation resource location: %s%n", modelOperation.getResourceLocation());
});
}
} | |
shouldn't this be send.synchronously ? | public void run() {
runAsync().block();
} | runAsync().block(); | public void run() {
runAsync().block();
} | class PipelineSendTest extends RestProxyTestBase<CorePerfStressOptions> {
private final Supplier<BinaryData> binaryDataSupplier;
private final URL targetURL;
public PipelineSendTest(CorePerfStressOptions options) {
super(options);
binaryDataSupplier = createBinaryDataSupplier(options);
try {
targetURL = new URL(new URL(endpoint), "BinaryData");
} catch (MalformedURLException e) {
throw new UncheckedIOException(e);
}
}
@Override
@Override
public Mono<Void> runAsync() {
HttpRequest httpRequest = new HttpRequest(
HttpMethod.PUT, targetURL, new HttpHeaders(), binaryDataSupplier.get().toFluxByteBuffer());
return httpPipeline.send(httpRequest)
.then();
}
} | class PipelineSendTest extends RestProxyTestBase<CorePerfStressOptions> {
private final Supplier<BinaryData> binaryDataSupplier;
private final URL targetURL;
public PipelineSendTest(CorePerfStressOptions options) {
super(options);
binaryDataSupplier = createBinaryDataSupplier(options);
try {
targetURL = new URL(new URL(endpoint), "BinaryData");
} catch (MalformedURLException e) {
throw new UncheckedIOException(e);
}
}
@Override
@Override
public Mono<Void> runAsync() {
HttpRequest httpRequest = new HttpRequest(
HttpMethod.PUT, targetURL, new HttpHeaders(), binaryDataSupplier.get().toFluxByteBuffer());
return httpPipeline.send(httpRequest)
.then();
}
} |
This PR is targeting `main` branch. I'll be changing this in sync stack branch when I merge main there. This in main is going to be useful to get comparison between sync and sync-over-async. | public void run() {
runAsync().block();
} | runAsync().block(); | public void run() {
runAsync().block();
} | class PipelineSendTest extends RestProxyTestBase<CorePerfStressOptions> {
private final Supplier<BinaryData> binaryDataSupplier;
private final URL targetURL;
public PipelineSendTest(CorePerfStressOptions options) {
super(options);
binaryDataSupplier = createBinaryDataSupplier(options);
try {
targetURL = new URL(new URL(endpoint), "BinaryData");
} catch (MalformedURLException e) {
throw new UncheckedIOException(e);
}
}
@Override
@Override
public Mono<Void> runAsync() {
HttpRequest httpRequest = new HttpRequest(
HttpMethod.PUT, targetURL, new HttpHeaders(), binaryDataSupplier.get().toFluxByteBuffer());
return httpPipeline.send(httpRequest)
.then();
}
} | class PipelineSendTest extends RestProxyTestBase<CorePerfStressOptions> {
private final Supplier<BinaryData> binaryDataSupplier;
private final URL targetURL;
public PipelineSendTest(CorePerfStressOptions options) {
super(options);
binaryDataSupplier = createBinaryDataSupplier(options);
try {
targetURL = new URL(new URL(endpoint), "BinaryData");
} catch (MalformedURLException e) {
throw new UncheckedIOException(e);
}
}
@Override
@Override
public Mono<Void> runAsync() {
HttpRequest httpRequest = new HttpRequest(
HttpMethod.PUT, targetURL, new HttpHeaders(), binaryDataSupplier.get().toFluxByteBuffer());
return httpPipeline.send(httpRequest)
.then();
}
} |
there is no behavior change. released mgmt SDKs is using same 7.2 latest code is 7.3-preview | private void init() {
if (innerModel().properties().vaultUri() != null) {
final String vaultUrl = vaultUri();
this.secretClient =
new SecretClientBuilder()
.vaultUrl(vaultUrl)
.pipeline(vaultHttpPipeline)
.serviceVersion(SecretServiceVersion.V7_2)
.buildAsyncClient();
this.keyClient =
new KeyClientBuilder()
.vaultUrl(vaultUrl)
.pipeline(vaultHttpPipeline)
.serviceVersion(KeyServiceVersion.V7_2)
.buildAsyncClient();
}
} | .serviceVersion(SecretServiceVersion.V7_2) | private void init() {
if (innerModel().properties().vaultUri() != null) {
final String vaultUrl = vaultUri();
this.secretClient =
new SecretClientBuilder()
.vaultUrl(vaultUrl)
.pipeline(vaultHttpPipeline)
.serviceVersion(SecretServiceVersion.V7_2)
.buildAsyncClient();
this.keyClient =
new KeyClientBuilder()
.vaultUrl(vaultUrl)
.pipeline(vaultHttpPipeline)
.serviceVersion(KeyServiceVersion.V7_2)
.buildAsyncClient();
}
} | class VaultImpl extends GroupableResourceImpl<Vault, VaultInner, VaultImpl, KeyVaultManager>
implements Vault, Vault.Definition, Vault.Update {
private final ClientLogger logger = new ClientLogger(this.getClass());
private AuthorizationManager authorizationManager;
private List<AccessPolicyImpl> accessPolicies;
private SecretAsyncClient secretClient;
private KeyAsyncClient keyClient;
private HttpPipeline vaultHttpPipeline;
private Keys keys;
private Secrets secrets;
VaultImpl(String key, VaultInner innerObject, KeyVaultManager manager, AuthorizationManager authorizationManager) {
super(key, innerObject, manager);
this.authorizationManager = authorizationManager;
this.accessPolicies = new ArrayList<>();
if (innerObject != null
&& innerObject.properties() != null
&& innerObject.properties().accessPolicies() != null) {
for (AccessPolicyEntry entry : innerObject.properties().accessPolicies()) {
this.accessPolicies.add(new AccessPolicyImpl(entry, this));
}
}
vaultHttpPipeline = manager().httpPipeline();
init();
}
@Override
public HttpPipeline vaultHttpPipeline() {
return vaultHttpPipeline;
}
public SecretAsyncClient secretClient() {
return secretClient;
}
@Override
public KeyAsyncClient keyClient() {
return keyClient;
}
@Override
public Keys keys() {
if (keys == null) {
keys = new KeysImpl(keyClient, this);
}
return keys;
}
@Override
public Secrets secrets() {
if (secrets == null) {
secrets = new SecretsImpl(secretClient, this);
}
return secrets;
}
@Override
public String vaultUri() {
if (innerModel().properties() == null) {
return null;
}
return innerModel().properties().vaultUri();
}
@Override
public String tenantId() {
if (innerModel().properties() == null) {
return null;
}
if (innerModel().properties().tenantId() == null) {
return null;
}
return innerModel().properties().tenantId().toString();
}
@Override
public Sku sku() {
if (innerModel().properties() == null) {
return null;
}
return innerModel().properties().sku();
}
@Override
public List<AccessPolicy> accessPolicies() {
AccessPolicy[] array = new AccessPolicy[accessPolicies.size()];
return Arrays.asList(accessPolicies.toArray(array));
}
@Override
public boolean roleBasedAccessControlEnabled() {
if (innerModel().properties() == null) {
return false;
}
return ResourceManagerUtils.toPrimitiveBoolean(innerModel().properties().enableRbacAuthorization());
}
@Override
public boolean enabledForDeployment() {
if (innerModel().properties() == null) {
return false;
}
return ResourceManagerUtils.toPrimitiveBoolean(innerModel().properties().enabledForDeployment());
}
@Override
public boolean enabledForDiskEncryption() {
if (innerModel().properties() == null) {
return false;
}
return ResourceManagerUtils.toPrimitiveBoolean(innerModel().properties().enabledForDiskEncryption());
}
@Override
public boolean enabledForTemplateDeployment() {
if (innerModel().properties() == null) {
return false;
}
return ResourceManagerUtils.toPrimitiveBoolean(innerModel().properties().enabledForTemplateDeployment());
}
@Override
public boolean softDeleteEnabled() {
if (innerModel().properties() == null) {
return false;
}
return ResourceManagerUtils.toPrimitiveBoolean(innerModel().properties().enableSoftDelete());
}
@Override
public boolean purgeProtectionEnabled() {
if (innerModel().properties() == null) {
return false;
}
return ResourceManagerUtils.toPrimitiveBoolean(innerModel().properties().enablePurgeProtection());
}
@Override
public VaultImpl withEmptyAccessPolicy() {
this.accessPolicies = new ArrayList<>();
return this;
}
@Override
public VaultImpl withoutAccessPolicy(String objectId) {
for (AccessPolicyImpl entry : this.accessPolicies) {
if (entry.objectId().equals(objectId)) {
accessPolicies.remove(entry);
break;
}
}
return this;
}
@Override
public VaultImpl withAccessPolicy(AccessPolicy accessPolicy) {
accessPolicies.add((AccessPolicyImpl) accessPolicy);
return this;
}
@Override
public AccessPolicyImpl defineAccessPolicy() {
return new AccessPolicyImpl(new AccessPolicyEntry(), this);
}
@Override
public VaultImpl withRoleBasedAccessControl() {
innerModel().properties().withEnableRbacAuthorization(true);
return this;
}
@Override
public VaultImpl withoutRoleBasedAccessControl() {
innerModel().properties().withEnableRbacAuthorization(false);
return this;
}
@Override
public AccessPolicyImpl updateAccessPolicy(String objectId) {
for (AccessPolicyImpl entry : this.accessPolicies) {
if (entry.objectId().equals(objectId)) {
return entry;
}
}
throw logger.logExceptionAsError(
new NoSuchElementException(String.format("Identity %s not found in the access policies.", objectId)));
}
@Override
public VaultImpl withDeploymentEnabled() {
innerModel().properties().withEnabledForDeployment(true);
return this;
}
@Override
public VaultImpl withDiskEncryptionEnabled() {
innerModel().properties().withEnabledForDiskEncryption(true);
return this;
}
@Override
public VaultImpl withTemplateDeploymentEnabled() {
innerModel().properties().withEnabledForTemplateDeployment(true);
return this;
}
@Override
public VaultImpl withSoftDeleteEnabled() {
innerModel().properties().withEnableSoftDelete(true);
return this;
}
@Override
public VaultImpl withPurgeProtectionEnabled() {
innerModel().properties().withEnablePurgeProtection(true);
return this;
}
@Override
public VaultImpl withDeploymentDisabled() {
innerModel().properties().withEnabledForDeployment(false);
return this;
}
@Override
public VaultImpl withDiskEncryptionDisabled() {
innerModel().properties().withEnabledForDiskEncryption(false);
return this;
}
@Override
public VaultImpl withTemplateDeploymentDisabled() {
innerModel().properties().withEnabledForTemplateDeployment(false);
return this;
}
@Override
public VaultImpl withSku(SkuName skuName) {
if (innerModel().properties() == null) {
innerModel().withProperties(new VaultProperties());
}
innerModel().properties().withSku(new Sku().withName(skuName).withFamily(SkuFamily.A));
return this;
}
private Mono<List<AccessPolicy>> populateAccessPolicies() {
List<Mono<?>> observables = new ArrayList<>();
for (final AccessPolicyImpl accessPolicy : accessPolicies) {
if (accessPolicy.objectId() == null) {
if (accessPolicy.userPrincipalName() != null) {
observables
.add(
authorizationManager
.users()
.getByNameAsync(accessPolicy.userPrincipalName())
.subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler())
.doOnNext(user -> accessPolicy.forObjectId(user.id()))
.switchIfEmpty(
Mono
.error(
new ManagementException(
String
.format(
"User principal name %s is not found in tenant %s",
accessPolicy.userPrincipalName(),
authorizationManager.tenantId()),
null))));
} else if (accessPolicy.servicePrincipalName() != null) {
observables
.add(
authorizationManager
.servicePrincipals()
.getByNameAsync(accessPolicy.servicePrincipalName())
.subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler())
.doOnNext(sp -> accessPolicy.forObjectId(sp.id()))
.switchIfEmpty(
Mono
.error(
new ManagementException(
String
.format(
"Service principal name %s is not found in tenant %s",
accessPolicy.servicePrincipalName(),
authorizationManager.tenantId()),
null))));
} else {
throw logger.logExceptionAsError(
new IllegalArgumentException("Access policy must specify object ID."));
}
}
}
if (observables.isEmpty()) {
return Mono.just(accessPolicies());
} else {
return Mono.zip(observables, args -> accessPolicies());
}
}
@Override
public Mono<Vault> createResourceAsync() {
final VaultsClient client = this.manager().serviceClient().getVaults();
return populateAccessPolicies()
.then(
Mono
.defer(
() -> {
VaultCreateOrUpdateParameters parameters = new VaultCreateOrUpdateParameters();
parameters.withLocation(regionName());
parameters.withProperties(innerModel().properties());
parameters.withTags(innerModel().tags());
parameters.properties().withAccessPolicies(new ArrayList<>());
for (AccessPolicy accessPolicy : accessPolicies) {
parameters.properties().accessPolicies().add(accessPolicy.innerModel());
}
return client.createOrUpdateAsync(resourceGroupName(), this.name(), parameters);
}))
.map(
inner -> {
this.setInner(inner);
init();
return this;
});
}
@Override
protected Mono<VaultInner> getInnerAsync() {
return this.manager().serviceClient().getVaults().getByResourceGroupAsync(resourceGroupName(), this.name());
}
@Override
public CreateMode createMode() {
return innerModel().properties().createMode();
}
@Override
public NetworkRuleSet networkRuleSet() {
return innerModel().properties().networkAcls();
}
@Override
public VaultImpl withAccessFromAllNetworks() {
if (innerModel().properties().networkAcls() == null) {
innerModel().properties().withNetworkAcls(new NetworkRuleSet());
}
innerModel().properties().networkAcls().withDefaultAction(NetworkRuleAction.ALLOW);
return this;
}
@Override
public VaultImpl withAccessFromSelectedNetworks() {
if (innerModel().properties().networkAcls() == null) {
innerModel().properties().withNetworkAcls(new NetworkRuleSet());
}
innerModel().properties().networkAcls().withDefaultAction(NetworkRuleAction.DENY);
return this;
}
/**
* Specifies that access to the storage account should be allowed from the given ip address or ip address range.
*
* @param ipAddressOrRange the ip address or ip address range in cidr format
* @return VaultImpl
*/
private VaultImpl withAccessAllowedFromIpAddressOrRange(String ipAddressOrRange) {
NetworkRuleSet networkRuleSet = innerModel().properties().networkAcls();
if (networkRuleSet.ipRules() == null) {
networkRuleSet.withIpRules(new ArrayList<>());
}
boolean found = false;
for (IpRule rule : networkRuleSet.ipRules()) {
if (rule.value().equalsIgnoreCase(ipAddressOrRange)) {
found = true;
break;
}
}
if (!found) {
networkRuleSet.ipRules().add(new IpRule().withValue(ipAddressOrRange));
}
return this;
}
@Override
public VaultImpl withAccessFromIpAddress(String ipAddress) {
return withAccessAllowedFromIpAddressOrRange(ipAddress);
}
@Override
public VaultImpl withAccessFromIpAddressRange(String ipAddressCidr) {
return withAccessAllowedFromIpAddressOrRange(ipAddressCidr);
}
@Override
public VaultImpl withAccessFromAzureServices() {
if (innerModel().properties().networkAcls() == null) {
innerModel().properties().withNetworkAcls(new NetworkRuleSet());
}
innerModel().properties().networkAcls().withBypass(NetworkRuleBypassOptions.AZURE_SERVICES);
return this;
}
@Override
public VaultImpl withBypass(NetworkRuleBypassOptions bypass) {
if (innerModel().properties().networkAcls() == null) {
innerModel().properties().withNetworkAcls(new NetworkRuleSet());
}
innerModel().properties().networkAcls().withBypass(bypass);
return this;
}
@Override
public VaultImpl withDefaultAction(NetworkRuleAction defaultAction) {
if (innerModel().properties().networkAcls() == null) {
innerModel().properties().withNetworkAcls(new NetworkRuleSet());
}
innerModel().properties().networkAcls().withDefaultAction(defaultAction);
return this;
}
@Override
public VaultImpl withVirtualNetworkRules(List<VirtualNetworkRule> virtualNetworkRules) {
if (innerModel().properties().networkAcls() == null) {
innerModel().properties().withNetworkAcls(new NetworkRuleSet());
}
innerModel().properties().networkAcls().withVirtualNetworkRules(virtualNetworkRules);
return this;
}
@Override
public PagedIterable<PrivateLinkResource> listPrivateLinkResources() {
return new PagedIterable<>(listPrivateLinkResourcesAsync());
}
@Override
public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() {
Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources()
.listByVaultWithResponseAsync(this.resourceGroupName(), this.name())
.map(response -> new SimpleResponse<>(response, response.getValue().value().stream()
.map(PrivateLinkResourceImpl::new)
.collect(Collectors.toList())));
return PagedConverter.convertListToPagedFlux(retList);
}
@Override
public void approvePrivateEndpointConnection(String privateEndpointConnectionName) {
approvePrivateEndpointConnectionAsync(privateEndpointConnectionName).block();
}
@Override
public Mono<Void> approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) {
return manager().serviceClient().getPrivateEndpointConnections().putAsync(
this.resourceGroupName(), this.name(), privateEndpointConnectionName,
new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState(
new PrivateLinkServiceConnectionState().withStatus(PrivateEndpointServiceConnectionStatus.APPROVED)))
.then();
}
@Override
public void rejectPrivateEndpointConnection(String privateEndpointConnectionName) {
rejectPrivateEndpointConnectionAsync(privateEndpointConnectionName).block();
}
@Override
public Mono<Void> rejectPrivateEndpointConnectionAsync(String privateEndpointConnectionName) {
return manager().serviceClient().getPrivateEndpointConnections().putAsync(
this.resourceGroupName(), this.name(), privateEndpointConnectionName,
new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState(
new PrivateLinkServiceConnectionState().withStatus(PrivateEndpointServiceConnectionStatus.REJECTED)))
.then();
}
private static final class PrivateLinkResourceImpl implements PrivateLinkResource {
private final com.azure.resourcemanager.keyvault.models.PrivateLinkResource innerModel;
private PrivateLinkResourceImpl(com.azure.resourcemanager.keyvault.models.PrivateLinkResource innerModel) {
this.innerModel = innerModel;
}
@Override
public String groupId() {
return innerModel.groupId();
}
@Override
public List<String> requiredMemberNames() {
return Collections.unmodifiableList(innerModel.requiredMembers());
}
@Override
public List<String> requiredDnsZoneNames() {
return Collections.unmodifiableList(innerModel.requiredZoneNames());
}
}
} | class VaultImpl extends GroupableResourceImpl<Vault, VaultInner, VaultImpl, KeyVaultManager>
implements Vault, Vault.Definition, Vault.Update {
private final ClientLogger logger = new ClientLogger(this.getClass());
private AuthorizationManager authorizationManager;
private List<AccessPolicyImpl> accessPolicies;
private SecretAsyncClient secretClient;
private KeyAsyncClient keyClient;
private HttpPipeline vaultHttpPipeline;
private Keys keys;
private Secrets secrets;
VaultImpl(String key, VaultInner innerObject, KeyVaultManager manager, AuthorizationManager authorizationManager) {
super(key, innerObject, manager);
this.authorizationManager = authorizationManager;
this.accessPolicies = new ArrayList<>();
if (innerObject != null
&& innerObject.properties() != null
&& innerObject.properties().accessPolicies() != null) {
for (AccessPolicyEntry entry : innerObject.properties().accessPolicies()) {
this.accessPolicies.add(new AccessPolicyImpl(entry, this));
}
}
vaultHttpPipeline = manager().httpPipeline();
init();
}
@Override
public HttpPipeline vaultHttpPipeline() {
return vaultHttpPipeline;
}
public SecretAsyncClient secretClient() {
return secretClient;
}
@Override
public KeyAsyncClient keyClient() {
return keyClient;
}
@Override
public Keys keys() {
if (keys == null) {
keys = new KeysImpl(keyClient, this);
}
return keys;
}
@Override
public Secrets secrets() {
if (secrets == null) {
secrets = new SecretsImpl(secretClient, this);
}
return secrets;
}
@Override
public String vaultUri() {
if (innerModel().properties() == null) {
return null;
}
return innerModel().properties().vaultUri();
}
@Override
public String tenantId() {
if (innerModel().properties() == null) {
return null;
}
if (innerModel().properties().tenantId() == null) {
return null;
}
return innerModel().properties().tenantId().toString();
}
@Override
public Sku sku() {
if (innerModel().properties() == null) {
return null;
}
return innerModel().properties().sku();
}
@Override
public List<AccessPolicy> accessPolicies() {
AccessPolicy[] array = new AccessPolicy[accessPolicies.size()];
return Arrays.asList(accessPolicies.toArray(array));
}
@Override
public boolean roleBasedAccessControlEnabled() {
if (innerModel().properties() == null) {
return false;
}
return ResourceManagerUtils.toPrimitiveBoolean(innerModel().properties().enableRbacAuthorization());
}
@Override
public boolean enabledForDeployment() {
if (innerModel().properties() == null) {
return false;
}
return ResourceManagerUtils.toPrimitiveBoolean(innerModel().properties().enabledForDeployment());
}
@Override
public boolean enabledForDiskEncryption() {
if (innerModel().properties() == null) {
return false;
}
return ResourceManagerUtils.toPrimitiveBoolean(innerModel().properties().enabledForDiskEncryption());
}
@Override
public boolean enabledForTemplateDeployment() {
if (innerModel().properties() == null) {
return false;
}
return ResourceManagerUtils.toPrimitiveBoolean(innerModel().properties().enabledForTemplateDeployment());
}
@Override
public boolean softDeleteEnabled() {
if (innerModel().properties() == null) {
return false;
}
return ResourceManagerUtils.toPrimitiveBoolean(innerModel().properties().enableSoftDelete());
}
@Override
public boolean purgeProtectionEnabled() {
if (innerModel().properties() == null) {
return false;
}
return ResourceManagerUtils.toPrimitiveBoolean(innerModel().properties().enablePurgeProtection());
}
@Override
public VaultImpl withEmptyAccessPolicy() {
this.accessPolicies = new ArrayList<>();
return this;
}
@Override
public VaultImpl withoutAccessPolicy(String objectId) {
for (AccessPolicyImpl entry : this.accessPolicies) {
if (entry.objectId().equals(objectId)) {
accessPolicies.remove(entry);
break;
}
}
return this;
}
@Override
public VaultImpl withAccessPolicy(AccessPolicy accessPolicy) {
accessPolicies.add((AccessPolicyImpl) accessPolicy);
return this;
}
@Override
public AccessPolicyImpl defineAccessPolicy() {
return new AccessPolicyImpl(new AccessPolicyEntry(), this);
}
@Override
public VaultImpl withRoleBasedAccessControl() {
innerModel().properties().withEnableRbacAuthorization(true);
return this;
}
@Override
public VaultImpl withoutRoleBasedAccessControl() {
innerModel().properties().withEnableRbacAuthorization(false);
return this;
}
@Override
public AccessPolicyImpl updateAccessPolicy(String objectId) {
for (AccessPolicyImpl entry : this.accessPolicies) {
if (entry.objectId().equals(objectId)) {
return entry;
}
}
throw logger.logExceptionAsError(
new NoSuchElementException(String.format("Identity %s not found in the access policies.", objectId)));
}
@Override
public VaultImpl withDeploymentEnabled() {
innerModel().properties().withEnabledForDeployment(true);
return this;
}
@Override
public VaultImpl withDiskEncryptionEnabled() {
innerModel().properties().withEnabledForDiskEncryption(true);
return this;
}
@Override
public VaultImpl withTemplateDeploymentEnabled() {
innerModel().properties().withEnabledForTemplateDeployment(true);
return this;
}
@Override
public VaultImpl withSoftDeleteEnabled() {
innerModel().properties().withEnableSoftDelete(true);
return this;
}
@Override
public VaultImpl withPurgeProtectionEnabled() {
innerModel().properties().withEnablePurgeProtection(true);
return this;
}
@Override
public VaultImpl withDeploymentDisabled() {
innerModel().properties().withEnabledForDeployment(false);
return this;
}
@Override
public VaultImpl withDiskEncryptionDisabled() {
innerModel().properties().withEnabledForDiskEncryption(false);
return this;
}
@Override
public VaultImpl withTemplateDeploymentDisabled() {
innerModel().properties().withEnabledForTemplateDeployment(false);
return this;
}
@Override
public VaultImpl withSku(SkuName skuName) {
if (innerModel().properties() == null) {
innerModel().withProperties(new VaultProperties());
}
innerModel().properties().withSku(new Sku().withName(skuName).withFamily(SkuFamily.A));
return this;
}
private Mono<List<AccessPolicy>> populateAccessPolicies() {
List<Mono<?>> observables = new ArrayList<>();
for (final AccessPolicyImpl accessPolicy : accessPolicies) {
if (accessPolicy.objectId() == null) {
if (accessPolicy.userPrincipalName() != null) {
observables
.add(
authorizationManager
.users()
.getByNameAsync(accessPolicy.userPrincipalName())
.subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler())
.doOnNext(user -> accessPolicy.forObjectId(user.id()))
.switchIfEmpty(
Mono
.error(
new ManagementException(
String
.format(
"User principal name %s is not found in tenant %s",
accessPolicy.userPrincipalName(),
authorizationManager.tenantId()),
null))));
} else if (accessPolicy.servicePrincipalName() != null) {
observables
.add(
authorizationManager
.servicePrincipals()
.getByNameAsync(accessPolicy.servicePrincipalName())
.subscribeOn(ResourceManagerUtils.InternalRuntimeContext.getReactorScheduler())
.doOnNext(sp -> accessPolicy.forObjectId(sp.id()))
.switchIfEmpty(
Mono
.error(
new ManagementException(
String
.format(
"Service principal name %s is not found in tenant %s",
accessPolicy.servicePrincipalName(),
authorizationManager.tenantId()),
null))));
} else {
throw logger.logExceptionAsError(
new IllegalArgumentException("Access policy must specify object ID."));
}
}
}
if (observables.isEmpty()) {
return Mono.just(accessPolicies());
} else {
return Mono.zip(observables, args -> accessPolicies());
}
}
@Override
public Mono<Vault> createResourceAsync() {
final VaultsClient client = this.manager().serviceClient().getVaults();
return populateAccessPolicies()
.then(
Mono
.defer(
() -> {
VaultCreateOrUpdateParameters parameters = new VaultCreateOrUpdateParameters();
parameters.withLocation(regionName());
parameters.withProperties(innerModel().properties());
parameters.withTags(innerModel().tags());
parameters.properties().withAccessPolicies(new ArrayList<>());
for (AccessPolicy accessPolicy : accessPolicies) {
parameters.properties().accessPolicies().add(accessPolicy.innerModel());
}
return client.createOrUpdateAsync(resourceGroupName(), this.name(), parameters);
}))
.map(
inner -> {
this.setInner(inner);
init();
return this;
});
}
@Override
protected Mono<VaultInner> getInnerAsync() {
return this.manager().serviceClient().getVaults().getByResourceGroupAsync(resourceGroupName(), this.name());
}
@Override
public CreateMode createMode() {
return innerModel().properties().createMode();
}
@Override
public NetworkRuleSet networkRuleSet() {
return innerModel().properties().networkAcls();
}
@Override
public VaultImpl withAccessFromAllNetworks() {
if (innerModel().properties().networkAcls() == null) {
innerModel().properties().withNetworkAcls(new NetworkRuleSet());
}
innerModel().properties().networkAcls().withDefaultAction(NetworkRuleAction.ALLOW);
return this;
}
@Override
public VaultImpl withAccessFromSelectedNetworks() {
if (innerModel().properties().networkAcls() == null) {
innerModel().properties().withNetworkAcls(new NetworkRuleSet());
}
innerModel().properties().networkAcls().withDefaultAction(NetworkRuleAction.DENY);
return this;
}
/**
* Specifies that access to the storage account should be allowed from the given ip address or ip address range.
*
* @param ipAddressOrRange the ip address or ip address range in cidr format
* @return VaultImpl
*/
private VaultImpl withAccessAllowedFromIpAddressOrRange(String ipAddressOrRange) {
NetworkRuleSet networkRuleSet = innerModel().properties().networkAcls();
if (networkRuleSet.ipRules() == null) {
networkRuleSet.withIpRules(new ArrayList<>());
}
boolean found = false;
for (IpRule rule : networkRuleSet.ipRules()) {
if (rule.value().equalsIgnoreCase(ipAddressOrRange)) {
found = true;
break;
}
}
if (!found) {
networkRuleSet.ipRules().add(new IpRule().withValue(ipAddressOrRange));
}
return this;
}
@Override
public VaultImpl withAccessFromIpAddress(String ipAddress) {
return withAccessAllowedFromIpAddressOrRange(ipAddress);
}
@Override
public VaultImpl withAccessFromIpAddressRange(String ipAddressCidr) {
return withAccessAllowedFromIpAddressOrRange(ipAddressCidr);
}
@Override
public VaultImpl withAccessFromAzureServices() {
if (innerModel().properties().networkAcls() == null) {
innerModel().properties().withNetworkAcls(new NetworkRuleSet());
}
innerModel().properties().networkAcls().withBypass(NetworkRuleBypassOptions.AZURE_SERVICES);
return this;
}
@Override
public VaultImpl withBypass(NetworkRuleBypassOptions bypass) {
if (innerModel().properties().networkAcls() == null) {
innerModel().properties().withNetworkAcls(new NetworkRuleSet());
}
innerModel().properties().networkAcls().withBypass(bypass);
return this;
}
@Override
public VaultImpl withDefaultAction(NetworkRuleAction defaultAction) {
if (innerModel().properties().networkAcls() == null) {
innerModel().properties().withNetworkAcls(new NetworkRuleSet());
}
innerModel().properties().networkAcls().withDefaultAction(defaultAction);
return this;
}
@Override
public VaultImpl withVirtualNetworkRules(List<VirtualNetworkRule> virtualNetworkRules) {
if (innerModel().properties().networkAcls() == null) {
innerModel().properties().withNetworkAcls(new NetworkRuleSet());
}
innerModel().properties().networkAcls().withVirtualNetworkRules(virtualNetworkRules);
return this;
}
@Override
public PagedIterable<PrivateLinkResource> listPrivateLinkResources() {
return new PagedIterable<>(listPrivateLinkResourcesAsync());
}
@Override
public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() {
Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources()
.listByVaultWithResponseAsync(this.resourceGroupName(), this.name())
.map(response -> new SimpleResponse<>(response, response.getValue().value().stream()
.map(PrivateLinkResourceImpl::new)
.collect(Collectors.toList())));
return PagedConverter.convertListToPagedFlux(retList);
}
@Override
public void approvePrivateEndpointConnection(String privateEndpointConnectionName) {
approvePrivateEndpointConnectionAsync(privateEndpointConnectionName).block();
}
@Override
public Mono<Void> approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) {
return manager().serviceClient().getPrivateEndpointConnections().putAsync(
this.resourceGroupName(), this.name(), privateEndpointConnectionName,
new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState(
new PrivateLinkServiceConnectionState().withStatus(PrivateEndpointServiceConnectionStatus.APPROVED)))
.then();
}
@Override
public void rejectPrivateEndpointConnection(String privateEndpointConnectionName) {
rejectPrivateEndpointConnectionAsync(privateEndpointConnectionName).block();
}
@Override
public Mono<Void> rejectPrivateEndpointConnectionAsync(String privateEndpointConnectionName) {
return manager().serviceClient().getPrivateEndpointConnections().putAsync(
this.resourceGroupName(), this.name(), privateEndpointConnectionName,
new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState(
new PrivateLinkServiceConnectionState().withStatus(PrivateEndpointServiceConnectionStatus.REJECTED)))
.then();
}
private static final class PrivateLinkResourceImpl implements PrivateLinkResource {
private final com.azure.resourcemanager.keyvault.models.PrivateLinkResource innerModel;
private PrivateLinkResourceImpl(com.azure.resourcemanager.keyvault.models.PrivateLinkResource innerModel) {
this.innerModel = innerModel;
}
@Override
public String groupId() {
return innerModel.groupId();
}
@Override
public List<String> requiredMemberNames() {
return Collections.unmodifiableList(innerModel.requiredMembers());
}
@Override
public List<String> requiredDnsZoneNames() {
return Collections.unmodifiableList(innerModel.requiredZoneNames());
}
}
} |
When will `producerFactoryCustomizer` be null? | public void addProducerFactoryCustomizer(EventHubsProducerFactoryCustomizer producerFactoryCustomizer) {
if (producerFactoryCustomizer != null) {
this.producerFactoryCustomizers.add(producerFactoryCustomizer);
}
} | if (producerFactoryCustomizer != null) { | public void addProducerFactoryCustomizer(EventHubsProducerFactoryCustomizer producerFactoryCustomizer) {
if (producerFactoryCustomizer != null) {
this.producerFactoryCustomizers.add(producerFactoryCustomizer);
}
} | class EventHubsMessageChannelBinder extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<EventHubsConsumerProperties>, ExtendedProducerProperties<EventHubsProducerProperties>, EventHubsChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, EventHubsConsumerProperties, EventHubsProducerProperties> {
private static final Logger LOGGER = LoggerFactory.getLogger(EventHubsMessageChannelBinder.class);
private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
private NamespaceProperties namespaceProperties;
private EventHubsTemplate eventHubsTemplate;
private CheckpointStore checkpointStore;
private DefaultEventHubsNamespaceProcessorFactory processorFactory;
private final List<EventHubsMessageListenerContainer> eventHubsMessageListenerContainers = new ArrayList<>();
private final InstrumentationManager instrumentationManager = new DefaultInstrumentationManager();
private EventHubsExtendedBindingProperties bindingProperties = new EventHubsExtendedBindingProperties();
private final Map<String, ExtendedProducerProperties<EventHubsProducerProperties>>
extendedProducerPropertiesMap = new ConcurrentHashMap<>();
private final List<EventHubsProducerFactoryCustomizer> producerFactoryCustomizers = new ArrayList<>();
private final List<EventHubsProcessorFactoryCustomizer> processorFactoryCustomizers = new ArrayList<>();
/**
* Construct a {@link EventHubsMessageChannelBinder} with the specified headers to embed and {@link EventHubsChannelProvisioner}.
*
* @param headersToEmbed the headers to embed
* @param provisioningProvider the provisioning provider
*/
public EventHubsMessageChannelBinder(String[] headersToEmbed, EventHubsChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(
ProducerDestination destination,
ExtendedProducerProperties<EventHubsProducerProperties> producerProperties,
MessageChannel errorChannel) {
extendedProducerPropertiesMap.put(destination.getName(), producerProperties);
Assert.notNull(getEventHubTemplate(), "eventHubsTemplate can't be null when create a producer");
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), this.eventHubsTemplate);
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout().toMillis());
handler.setSendFailureChannel(errorChannel);
String instrumentationId = Instrumentation.buildId(PRODUCER, destination.getName());
handler.setSendCallback(new InstrumentationSendCallback(instrumentationId, instrumentationManager));
if (producerProperties.isPartitioned()) {
handler.setPartitionIdExpression(
EXPRESSION_PARSER.parseExpression("headers['" + BinderHeaders.PARTITION_HEADER + "']"));
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
Assert.notNull(getProcessorFactory(), "processor factory can't be null when create a consumer");
boolean anonymous = !StringUtils.hasText(group);
if (anonymous) {
group = "anonymous." + UUID.randomUUID();
}
EventHubsContainerProperties containerProperties = createContainerProperties(destination, group, properties);
EventHubsMessageListenerContainer listenerContainer = new EventHubsMessageListenerContainer(
getProcessorFactory(), containerProperties);
this.eventHubsMessageListenerContainers.add(listenerContainer);
EventHubsInboundChannelAdapter inboundAdapter;
if (properties.isBatchMode()) {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer, ListenerMode.BATCH);
} else {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer);
}
inboundAdapter.setBeanFactory(getBeanFactory());
String instrumentationId = Instrumentation.buildId(CONSUMER, destination.getName() + "/" + group);
inboundAdapter.setInstrumentationManager(instrumentationManager);
inboundAdapter.setInstrumentationId(instrumentationId);
ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties);
inboundAdapter.setErrorChannel(errorInfrastructure.getErrorChannel());
return inboundAdapter;
}
/**
* Create {@link EventHubsContainerProperties} from the extended {@link EventHubsConsumerProperties}.
* @param destination reference to the consumer destination.
* @param group the consumer group.
* @param properties the consumer properties.
* @return the {@link EventHubsContainerProperties}.
*/
private EventHubsContainerProperties createContainerProperties(
ConsumerDestination destination,
String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
EventHubsContainerProperties containerProperties = new EventHubsContainerProperties();
AzurePropertiesUtils.copyAzureCommonProperties(properties.getExtension(), containerProperties);
ProcessorPropertiesMerger.copyProcessorPropertiesIfNotNull(properties.getExtension(), containerProperties);
containerProperties.setEventHubName(destination.getName());
containerProperties.setConsumerGroup(group);
containerProperties.setCheckpointConfig(properties.getExtension().getCheckpoint());
return containerProperties;
}
@Override
public EventHubsConsumerProperties getExtendedConsumerProperties(String destination) {
return this.bindingProperties.getExtendedConsumerProperties(destination);
}
@Override
public EventHubsProducerProperties getExtendedProducerProperties(String destination) {
return this.bindingProperties.getExtendedProducerProperties(destination);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
/**
* Set binding properties.
*
* @param bindingProperties the binding properties
*/
public void setBindingProperties(EventHubsExtendedBindingProperties bindingProperties) {
this.bindingProperties = bindingProperties;
}
private PropertiesSupplier<String, ProducerProperties> getProducerPropertiesSupplier() {
return key -> {
if (this.extendedProducerPropertiesMap.containsKey(key)) {
EventHubsProducerProperties producerProperties = this.extendedProducerPropertiesMap.get(key)
.getExtension();
producerProperties.setEventHubName(key);
return producerProperties;
} else {
LOGGER.debug("Can't find extended properties for {}", key);
return null;
}
};
}
private EventHubsTemplate getEventHubTemplate() {
if (this.eventHubsTemplate == null) {
DefaultEventHubsNamespaceProducerFactory factory = new DefaultEventHubsNamespaceProducerFactory(
this.namespaceProperties, getProducerPropertiesSupplier());
producerFactoryCustomizers.forEach(customizer -> customizer.customize(factory));
factory.addListener((name, producerAsyncClient) -> {
DefaultInstrumentation instrumentation = new DefaultInstrumentation(name, PRODUCER);
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
this.eventHubsTemplate = new EventHubsTemplate(factory);
}
return this.eventHubsTemplate;
}
private EventHubsProcessorFactory getProcessorFactory() {
if (this.processorFactory == null) {
this.processorFactory = new DefaultEventHubsNamespaceProcessorFactory(
this.checkpointStore, this.namespaceProperties);
processorFactoryCustomizers.forEach(customizer -> customizer.customize(processorFactory));
processorFactory.addListener((name, consumerGroup, processorClient) -> {
String instrumentationName = name + "/" + consumerGroup;
Instrumentation instrumentation = new EventHubsProcessorInstrumentation(instrumentationName, CONSUMER, Duration.ofMinutes(2));
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
}
return this.processorFactory;
}
/**
* Set namespace properties.
*
* @param namespaceProperties the namespace properties
*/
public void setNamespaceProperties(NamespaceProperties namespaceProperties) {
this.namespaceProperties = namespaceProperties;
}
/**
* Set checkpoint store.
*
* @param checkpointStore the checkpoint store
*/
public void setCheckpointStore(CheckpointStore checkpointStore) {
this.checkpointStore = checkpointStore;
}
/**
* Get instrumentation manager.
*
* @return instrumentationManager the instrumentation manager
* @see InstrumentationManager
*/
InstrumentationManager getInstrumentationManager() {
return instrumentationManager;
}
/**
* Add a producer factory customizer.
*
* @param producerFactoryCustomizer The producer factory customizer to add.
*/
/**
* Add a processor factory customizer.
*
* @param processorFactoryCustomizer The processor factory customizer to add.
*/
public void addProcessorFactoryCustomizer(EventHubsProcessorFactoryCustomizer processorFactoryCustomizer) {
if (processorFactoryCustomizer != null) {
this.processorFactoryCustomizers.add(processorFactoryCustomizer);
}
}
} | class EventHubsMessageChannelBinder extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<EventHubsConsumerProperties>, ExtendedProducerProperties<EventHubsProducerProperties>, EventHubsChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, EventHubsConsumerProperties, EventHubsProducerProperties> {
private static final Logger LOGGER = LoggerFactory.getLogger(EventHubsMessageChannelBinder.class);
private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
private NamespaceProperties namespaceProperties;
private EventHubsTemplate eventHubsTemplate;
private CheckpointStore checkpointStore;
private DefaultEventHubsNamespaceProcessorFactory processorFactory;
private final List<EventHubsMessageListenerContainer> eventHubsMessageListenerContainers = new ArrayList<>();
private final InstrumentationManager instrumentationManager = new DefaultInstrumentationManager();
private EventHubsExtendedBindingProperties bindingProperties = new EventHubsExtendedBindingProperties();
private final Map<String, ExtendedProducerProperties<EventHubsProducerProperties>>
extendedProducerPropertiesMap = new ConcurrentHashMap<>();
private final List<EventHubsProducerFactoryCustomizer> producerFactoryCustomizers = new ArrayList<>();
private final List<EventHubsProcessorFactoryCustomizer> processorFactoryCustomizers = new ArrayList<>();
/**
* Construct a {@link EventHubsMessageChannelBinder} with the specified headers to embed and {@link EventHubsChannelProvisioner}.
*
* @param headersToEmbed the headers to embed
* @param provisioningProvider the provisioning provider
*/
public EventHubsMessageChannelBinder(String[] headersToEmbed, EventHubsChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(
ProducerDestination destination,
ExtendedProducerProperties<EventHubsProducerProperties> producerProperties,
MessageChannel errorChannel) {
extendedProducerPropertiesMap.put(destination.getName(), producerProperties);
Assert.notNull(getEventHubTemplate(), "eventHubsTemplate can't be null when create a producer");
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), this.eventHubsTemplate);
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout().toMillis());
handler.setSendFailureChannel(errorChannel);
String instrumentationId = Instrumentation.buildId(PRODUCER, destination.getName());
handler.setSendCallback(new InstrumentationSendCallback(instrumentationId, instrumentationManager));
if (producerProperties.isPartitioned()) {
handler.setPartitionIdExpression(
EXPRESSION_PARSER.parseExpression("headers['" + BinderHeaders.PARTITION_HEADER + "']"));
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
Assert.notNull(getProcessorFactory(), "processor factory can't be null when create a consumer");
boolean anonymous = !StringUtils.hasText(group);
if (anonymous) {
group = "anonymous." + UUID.randomUUID();
}
EventHubsContainerProperties containerProperties = createContainerProperties(destination, group, properties);
EventHubsMessageListenerContainer listenerContainer = new EventHubsMessageListenerContainer(
getProcessorFactory(), containerProperties);
this.eventHubsMessageListenerContainers.add(listenerContainer);
EventHubsInboundChannelAdapter inboundAdapter;
if (properties.isBatchMode()) {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer, ListenerMode.BATCH);
} else {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer);
}
inboundAdapter.setBeanFactory(getBeanFactory());
String instrumentationId = Instrumentation.buildId(CONSUMER, destination.getName() + "/" + group);
inboundAdapter.setInstrumentationManager(instrumentationManager);
inboundAdapter.setInstrumentationId(instrumentationId);
ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties);
inboundAdapter.setErrorChannel(errorInfrastructure.getErrorChannel());
return inboundAdapter;
}
/**
* Create {@link EventHubsContainerProperties} from the extended {@link EventHubsConsumerProperties}.
* @param destination reference to the consumer destination.
* @param group the consumer group.
* @param properties the consumer properties.
* @return the {@link EventHubsContainerProperties}.
*/
private EventHubsContainerProperties createContainerProperties(
ConsumerDestination destination,
String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
EventHubsContainerProperties containerProperties = new EventHubsContainerProperties();
AzurePropertiesUtils.copyAzureCommonProperties(properties.getExtension(), containerProperties);
ProcessorPropertiesMerger.copyProcessorPropertiesIfNotNull(properties.getExtension(), containerProperties);
containerProperties.setEventHubName(destination.getName());
containerProperties.setConsumerGroup(group);
containerProperties.setCheckpointConfig(properties.getExtension().getCheckpoint());
return containerProperties;
}
@Override
public EventHubsConsumerProperties getExtendedConsumerProperties(String destination) {
return this.bindingProperties.getExtendedConsumerProperties(destination);
}
@Override
public EventHubsProducerProperties getExtendedProducerProperties(String destination) {
return this.bindingProperties.getExtendedProducerProperties(destination);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
/**
* Set binding properties.
*
* @param bindingProperties the binding properties
*/
public void setBindingProperties(EventHubsExtendedBindingProperties bindingProperties) {
this.bindingProperties = bindingProperties;
}
private PropertiesSupplier<String, ProducerProperties> getProducerPropertiesSupplier() {
return key -> {
if (this.extendedProducerPropertiesMap.containsKey(key)) {
EventHubsProducerProperties producerProperties = this.extendedProducerPropertiesMap.get(key)
.getExtension();
producerProperties.setEventHubName(key);
return producerProperties;
} else {
LOGGER.debug("Can't find extended properties for {}", key);
return null;
}
};
}
private EventHubsTemplate getEventHubTemplate() {
if (this.eventHubsTemplate == null) {
DefaultEventHubsNamespaceProducerFactory factory = new DefaultEventHubsNamespaceProducerFactory(
this.namespaceProperties, getProducerPropertiesSupplier());
producerFactoryCustomizers.forEach(customizer -> customizer.customize(factory));
factory.addListener((name, producerAsyncClient) -> {
DefaultInstrumentation instrumentation = new DefaultInstrumentation(name, PRODUCER);
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
this.eventHubsTemplate = new EventHubsTemplate(factory);
}
return this.eventHubsTemplate;
}
private EventHubsProcessorFactory getProcessorFactory() {
if (this.processorFactory == null) {
this.processorFactory = new DefaultEventHubsNamespaceProcessorFactory(
this.checkpointStore, this.namespaceProperties);
processorFactoryCustomizers.forEach(customizer -> customizer.customize(processorFactory));
processorFactory.addListener((name, consumerGroup, processorClient) -> {
String instrumentationName = name + "/" + consumerGroup;
Instrumentation instrumentation = new EventHubsProcessorInstrumentation(instrumentationName, CONSUMER, Duration.ofMinutes(2));
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
}
return this.processorFactory;
}
/**
* Set namespace properties.
*
* @param namespaceProperties the namespace properties
*/
public void setNamespaceProperties(NamespaceProperties namespaceProperties) {
this.namespaceProperties = namespaceProperties;
}
/**
* Set checkpoint store.
*
* @param checkpointStore the checkpoint store
*/
public void setCheckpointStore(CheckpointStore checkpointStore) {
this.checkpointStore = checkpointStore;
}
/**
* Get instrumentation manager.
*
* @return instrumentationManager the instrumentation manager
* @see InstrumentationManager
*/
InstrumentationManager getInstrumentationManager() {
return instrumentationManager;
}
/**
* Add a producer factory customizer.
*
* @param producerFactoryCustomizer The producer factory customizer to add.
*/
/**
* Add a processor factory customizer.
*
* @param processorFactoryCustomizer The processor factory customizer to add.
*/
public void addProcessorFactoryCustomizer(EventHubsProcessorFactoryCustomizer processorFactoryCustomizer) {
if (processorFactoryCustomizer != null) {
this.processorFactoryCustomizers.add(processorFactoryCustomizer);
}
}
} |
Do we need to consider thread-safe here? | public void addProducerFactoryCustomizer(EventHubsProducerFactoryCustomizer producerFactoryCustomizer) {
if (producerFactoryCustomizer != null) {
this.producerFactoryCustomizers.add(producerFactoryCustomizer);
}
} | this.producerFactoryCustomizers.add(producerFactoryCustomizer); | public void addProducerFactoryCustomizer(EventHubsProducerFactoryCustomizer producerFactoryCustomizer) {
if (producerFactoryCustomizer != null) {
this.producerFactoryCustomizers.add(producerFactoryCustomizer);
}
} | class EventHubsMessageChannelBinder extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<EventHubsConsumerProperties>, ExtendedProducerProperties<EventHubsProducerProperties>, EventHubsChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, EventHubsConsumerProperties, EventHubsProducerProperties> {
private static final Logger LOGGER = LoggerFactory.getLogger(EventHubsMessageChannelBinder.class);
private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
private NamespaceProperties namespaceProperties;
private EventHubsTemplate eventHubsTemplate;
private CheckpointStore checkpointStore;
private DefaultEventHubsNamespaceProcessorFactory processorFactory;
private final List<EventHubsMessageListenerContainer> eventHubsMessageListenerContainers = new ArrayList<>();
private final InstrumentationManager instrumentationManager = new DefaultInstrumentationManager();
private EventHubsExtendedBindingProperties bindingProperties = new EventHubsExtendedBindingProperties();
private final Map<String, ExtendedProducerProperties<EventHubsProducerProperties>>
extendedProducerPropertiesMap = new ConcurrentHashMap<>();
private final List<EventHubsProducerFactoryCustomizer> producerFactoryCustomizers = new ArrayList<>();
private final List<EventHubsProcessorFactoryCustomizer> processorFactoryCustomizers = new ArrayList<>();
/**
* Construct a {@link EventHubsMessageChannelBinder} with the specified headers to embed and {@link EventHubsChannelProvisioner}.
*
* @param headersToEmbed the headers to embed
* @param provisioningProvider the provisioning provider
*/
public EventHubsMessageChannelBinder(String[] headersToEmbed, EventHubsChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(
ProducerDestination destination,
ExtendedProducerProperties<EventHubsProducerProperties> producerProperties,
MessageChannel errorChannel) {
extendedProducerPropertiesMap.put(destination.getName(), producerProperties);
Assert.notNull(getEventHubTemplate(), "eventHubsTemplate can't be null when create a producer");
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), this.eventHubsTemplate);
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout().toMillis());
handler.setSendFailureChannel(errorChannel);
String instrumentationId = Instrumentation.buildId(PRODUCER, destination.getName());
handler.setSendCallback(new InstrumentationSendCallback(instrumentationId, instrumentationManager));
if (producerProperties.isPartitioned()) {
handler.setPartitionIdExpression(
EXPRESSION_PARSER.parseExpression("headers['" + BinderHeaders.PARTITION_HEADER + "']"));
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
Assert.notNull(getProcessorFactory(), "processor factory can't be null when create a consumer");
boolean anonymous = !StringUtils.hasText(group);
if (anonymous) {
group = "anonymous." + UUID.randomUUID();
}
EventHubsContainerProperties containerProperties = createContainerProperties(destination, group, properties);
EventHubsMessageListenerContainer listenerContainer = new EventHubsMessageListenerContainer(
getProcessorFactory(), containerProperties);
this.eventHubsMessageListenerContainers.add(listenerContainer);
EventHubsInboundChannelAdapter inboundAdapter;
if (properties.isBatchMode()) {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer, ListenerMode.BATCH);
} else {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer);
}
inboundAdapter.setBeanFactory(getBeanFactory());
String instrumentationId = Instrumentation.buildId(CONSUMER, destination.getName() + "/" + group);
inboundAdapter.setInstrumentationManager(instrumentationManager);
inboundAdapter.setInstrumentationId(instrumentationId);
ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties);
inboundAdapter.setErrorChannel(errorInfrastructure.getErrorChannel());
return inboundAdapter;
}
/**
* Create {@link EventHubsContainerProperties} from the extended {@link EventHubsConsumerProperties}.
* @param destination reference to the consumer destination.
* @param group the consumer group.
* @param properties the consumer properties.
* @return the {@link EventHubsContainerProperties}.
*/
private EventHubsContainerProperties createContainerProperties(
ConsumerDestination destination,
String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
EventHubsContainerProperties containerProperties = new EventHubsContainerProperties();
AzurePropertiesUtils.copyAzureCommonProperties(properties.getExtension(), containerProperties);
ProcessorPropertiesMerger.copyProcessorPropertiesIfNotNull(properties.getExtension(), containerProperties);
containerProperties.setEventHubName(destination.getName());
containerProperties.setConsumerGroup(group);
containerProperties.setCheckpointConfig(properties.getExtension().getCheckpoint());
return containerProperties;
}
@Override
public EventHubsConsumerProperties getExtendedConsumerProperties(String destination) {
return this.bindingProperties.getExtendedConsumerProperties(destination);
}
@Override
public EventHubsProducerProperties getExtendedProducerProperties(String destination) {
return this.bindingProperties.getExtendedProducerProperties(destination);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
/**
* Set binding properties.
*
* @param bindingProperties the binding properties
*/
public void setBindingProperties(EventHubsExtendedBindingProperties bindingProperties) {
this.bindingProperties = bindingProperties;
}
private PropertiesSupplier<String, ProducerProperties> getProducerPropertiesSupplier() {
return key -> {
if (this.extendedProducerPropertiesMap.containsKey(key)) {
EventHubsProducerProperties producerProperties = this.extendedProducerPropertiesMap.get(key)
.getExtension();
producerProperties.setEventHubName(key);
return producerProperties;
} else {
LOGGER.debug("Can't find extended properties for {}", key);
return null;
}
};
}
private EventHubsTemplate getEventHubTemplate() {
if (this.eventHubsTemplate == null) {
DefaultEventHubsNamespaceProducerFactory factory = new DefaultEventHubsNamespaceProducerFactory(
this.namespaceProperties, getProducerPropertiesSupplier());
producerFactoryCustomizers.forEach(customizer -> customizer.customize(factory));
factory.addListener((name, producerAsyncClient) -> {
DefaultInstrumentation instrumentation = new DefaultInstrumentation(name, PRODUCER);
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
this.eventHubsTemplate = new EventHubsTemplate(factory);
}
return this.eventHubsTemplate;
}
private EventHubsProcessorFactory getProcessorFactory() {
if (this.processorFactory == null) {
this.processorFactory = new DefaultEventHubsNamespaceProcessorFactory(
this.checkpointStore, this.namespaceProperties);
processorFactoryCustomizers.forEach(customizer -> customizer.customize(processorFactory));
processorFactory.addListener((name, consumerGroup, processorClient) -> {
String instrumentationName = name + "/" + consumerGroup;
Instrumentation instrumentation = new EventHubsProcessorInstrumentation(instrumentationName, CONSUMER, Duration.ofMinutes(2));
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
}
return this.processorFactory;
}
/**
* Set namespace properties.
*
* @param namespaceProperties the namespace properties
*/
public void setNamespaceProperties(NamespaceProperties namespaceProperties) {
this.namespaceProperties = namespaceProperties;
}
/**
* Set checkpoint store.
*
* @param checkpointStore the checkpoint store
*/
public void setCheckpointStore(CheckpointStore checkpointStore) {
this.checkpointStore = checkpointStore;
}
/**
* Get instrumentation manager.
*
* @return instrumentationManager the instrumentation manager
* @see InstrumentationManager
*/
InstrumentationManager getInstrumentationManager() {
return instrumentationManager;
}
/**
* Add a producer factory customizer.
*
* @param producerFactoryCustomizer The producer factory customizer to add.
*/
/**
* Add a processor factory customizer.
*
* @param processorFactoryCustomizer The processor factory customizer to add.
*/
public void addProcessorFactoryCustomizer(EventHubsProcessorFactoryCustomizer processorFactoryCustomizer) {
if (processorFactoryCustomizer != null) {
this.processorFactoryCustomizers.add(processorFactoryCustomizer);
}
}
} | class EventHubsMessageChannelBinder extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<EventHubsConsumerProperties>, ExtendedProducerProperties<EventHubsProducerProperties>, EventHubsChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, EventHubsConsumerProperties, EventHubsProducerProperties> {
private static final Logger LOGGER = LoggerFactory.getLogger(EventHubsMessageChannelBinder.class);
private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
private NamespaceProperties namespaceProperties;
private EventHubsTemplate eventHubsTemplate;
private CheckpointStore checkpointStore;
private DefaultEventHubsNamespaceProcessorFactory processorFactory;
private final List<EventHubsMessageListenerContainer> eventHubsMessageListenerContainers = new ArrayList<>();
private final InstrumentationManager instrumentationManager = new DefaultInstrumentationManager();
private EventHubsExtendedBindingProperties bindingProperties = new EventHubsExtendedBindingProperties();
private final Map<String, ExtendedProducerProperties<EventHubsProducerProperties>>
extendedProducerPropertiesMap = new ConcurrentHashMap<>();
private final List<EventHubsProducerFactoryCustomizer> producerFactoryCustomizers = new ArrayList<>();
private final List<EventHubsProcessorFactoryCustomizer> processorFactoryCustomizers = new ArrayList<>();
/**
* Construct a {@link EventHubsMessageChannelBinder} with the specified headers to embed and {@link EventHubsChannelProvisioner}.
*
* @param headersToEmbed the headers to embed
* @param provisioningProvider the provisioning provider
*/
public EventHubsMessageChannelBinder(String[] headersToEmbed, EventHubsChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(
ProducerDestination destination,
ExtendedProducerProperties<EventHubsProducerProperties> producerProperties,
MessageChannel errorChannel) {
extendedProducerPropertiesMap.put(destination.getName(), producerProperties);
Assert.notNull(getEventHubTemplate(), "eventHubsTemplate can't be null when create a producer");
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), this.eventHubsTemplate);
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout().toMillis());
handler.setSendFailureChannel(errorChannel);
String instrumentationId = Instrumentation.buildId(PRODUCER, destination.getName());
handler.setSendCallback(new InstrumentationSendCallback(instrumentationId, instrumentationManager));
if (producerProperties.isPartitioned()) {
handler.setPartitionIdExpression(
EXPRESSION_PARSER.parseExpression("headers['" + BinderHeaders.PARTITION_HEADER + "']"));
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
Assert.notNull(getProcessorFactory(), "processor factory can't be null when create a consumer");
boolean anonymous = !StringUtils.hasText(group);
if (anonymous) {
group = "anonymous." + UUID.randomUUID();
}
EventHubsContainerProperties containerProperties = createContainerProperties(destination, group, properties);
EventHubsMessageListenerContainer listenerContainer = new EventHubsMessageListenerContainer(
getProcessorFactory(), containerProperties);
this.eventHubsMessageListenerContainers.add(listenerContainer);
EventHubsInboundChannelAdapter inboundAdapter;
if (properties.isBatchMode()) {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer, ListenerMode.BATCH);
} else {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer);
}
inboundAdapter.setBeanFactory(getBeanFactory());
String instrumentationId = Instrumentation.buildId(CONSUMER, destination.getName() + "/" + group);
inboundAdapter.setInstrumentationManager(instrumentationManager);
inboundAdapter.setInstrumentationId(instrumentationId);
ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties);
inboundAdapter.setErrorChannel(errorInfrastructure.getErrorChannel());
return inboundAdapter;
}
/**
* Create {@link EventHubsContainerProperties} from the extended {@link EventHubsConsumerProperties}.
* @param destination reference to the consumer destination.
* @param group the consumer group.
* @param properties the consumer properties.
* @return the {@link EventHubsContainerProperties}.
*/
private EventHubsContainerProperties createContainerProperties(
ConsumerDestination destination,
String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
EventHubsContainerProperties containerProperties = new EventHubsContainerProperties();
AzurePropertiesUtils.copyAzureCommonProperties(properties.getExtension(), containerProperties);
ProcessorPropertiesMerger.copyProcessorPropertiesIfNotNull(properties.getExtension(), containerProperties);
containerProperties.setEventHubName(destination.getName());
containerProperties.setConsumerGroup(group);
containerProperties.setCheckpointConfig(properties.getExtension().getCheckpoint());
return containerProperties;
}
@Override
public EventHubsConsumerProperties getExtendedConsumerProperties(String destination) {
return this.bindingProperties.getExtendedConsumerProperties(destination);
}
@Override
public EventHubsProducerProperties getExtendedProducerProperties(String destination) {
return this.bindingProperties.getExtendedProducerProperties(destination);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
/**
* Set binding properties.
*
* @param bindingProperties the binding properties
*/
public void setBindingProperties(EventHubsExtendedBindingProperties bindingProperties) {
this.bindingProperties = bindingProperties;
}
private PropertiesSupplier<String, ProducerProperties> getProducerPropertiesSupplier() {
return key -> {
if (this.extendedProducerPropertiesMap.containsKey(key)) {
EventHubsProducerProperties producerProperties = this.extendedProducerPropertiesMap.get(key)
.getExtension();
producerProperties.setEventHubName(key);
return producerProperties;
} else {
LOGGER.debug("Can't find extended properties for {}", key);
return null;
}
};
}
private EventHubsTemplate getEventHubTemplate() {
if (this.eventHubsTemplate == null) {
DefaultEventHubsNamespaceProducerFactory factory = new DefaultEventHubsNamespaceProducerFactory(
this.namespaceProperties, getProducerPropertiesSupplier());
producerFactoryCustomizers.forEach(customizer -> customizer.customize(factory));
factory.addListener((name, producerAsyncClient) -> {
DefaultInstrumentation instrumentation = new DefaultInstrumentation(name, PRODUCER);
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
this.eventHubsTemplate = new EventHubsTemplate(factory);
}
return this.eventHubsTemplate;
}
private EventHubsProcessorFactory getProcessorFactory() {
if (this.processorFactory == null) {
this.processorFactory = new DefaultEventHubsNamespaceProcessorFactory(
this.checkpointStore, this.namespaceProperties);
processorFactoryCustomizers.forEach(customizer -> customizer.customize(processorFactory));
processorFactory.addListener((name, consumerGroup, processorClient) -> {
String instrumentationName = name + "/" + consumerGroup;
Instrumentation instrumentation = new EventHubsProcessorInstrumentation(instrumentationName, CONSUMER, Duration.ofMinutes(2));
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
}
return this.processorFactory;
}
/**
* Set namespace properties.
*
* @param namespaceProperties the namespace properties
*/
public void setNamespaceProperties(NamespaceProperties namespaceProperties) {
this.namespaceProperties = namespaceProperties;
}
/**
* Set checkpoint store.
*
* @param checkpointStore the checkpoint store
*/
public void setCheckpointStore(CheckpointStore checkpointStore) {
this.checkpointStore = checkpointStore;
}
/**
* Get instrumentation manager.
*
* @return instrumentationManager the instrumentation manager
* @see InstrumentationManager
*/
InstrumentationManager getInstrumentationManager() {
return instrumentationManager;
}
/**
* Add a producer factory customizer.
*
* @param producerFactoryCustomizer The producer factory customizer to add.
*/
/**
* Add a processor factory customizer.
*
* @param processorFactoryCustomizer The processor factory customizer to add.
*/
public void addProcessorFactoryCustomizer(EventHubsProcessorFactoryCustomizer processorFactoryCustomizer) {
if (processorFactoryCustomizer != null) {
this.processorFactoryCustomizers.add(processorFactoryCustomizer);
}
}
} |
this could be call by users | public void addProducerFactoryCustomizer(EventHubsProducerFactoryCustomizer producerFactoryCustomizer) {
if (producerFactoryCustomizer != null) {
this.producerFactoryCustomizers.add(producerFactoryCustomizer);
}
} | if (producerFactoryCustomizer != null) { | public void addProducerFactoryCustomizer(EventHubsProducerFactoryCustomizer producerFactoryCustomizer) {
if (producerFactoryCustomizer != null) {
this.producerFactoryCustomizers.add(producerFactoryCustomizer);
}
} | class EventHubsMessageChannelBinder extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<EventHubsConsumerProperties>, ExtendedProducerProperties<EventHubsProducerProperties>, EventHubsChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, EventHubsConsumerProperties, EventHubsProducerProperties> {
private static final Logger LOGGER = LoggerFactory.getLogger(EventHubsMessageChannelBinder.class);
private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
private NamespaceProperties namespaceProperties;
private EventHubsTemplate eventHubsTemplate;
private CheckpointStore checkpointStore;
private DefaultEventHubsNamespaceProcessorFactory processorFactory;
private final List<EventHubsMessageListenerContainer> eventHubsMessageListenerContainers = new ArrayList<>();
private final InstrumentationManager instrumentationManager = new DefaultInstrumentationManager();
private EventHubsExtendedBindingProperties bindingProperties = new EventHubsExtendedBindingProperties();
private final Map<String, ExtendedProducerProperties<EventHubsProducerProperties>>
extendedProducerPropertiesMap = new ConcurrentHashMap<>();
private final List<EventHubsProducerFactoryCustomizer> producerFactoryCustomizers = new ArrayList<>();
private final List<EventHubsProcessorFactoryCustomizer> processorFactoryCustomizers = new ArrayList<>();
/**
* Construct a {@link EventHubsMessageChannelBinder} with the specified headers to embed and {@link EventHubsChannelProvisioner}.
*
* @param headersToEmbed the headers to embed
* @param provisioningProvider the provisioning provider
*/
public EventHubsMessageChannelBinder(String[] headersToEmbed, EventHubsChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(
ProducerDestination destination,
ExtendedProducerProperties<EventHubsProducerProperties> producerProperties,
MessageChannel errorChannel) {
extendedProducerPropertiesMap.put(destination.getName(), producerProperties);
Assert.notNull(getEventHubTemplate(), "eventHubsTemplate can't be null when create a producer");
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), this.eventHubsTemplate);
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout().toMillis());
handler.setSendFailureChannel(errorChannel);
String instrumentationId = Instrumentation.buildId(PRODUCER, destination.getName());
handler.setSendCallback(new InstrumentationSendCallback(instrumentationId, instrumentationManager));
if (producerProperties.isPartitioned()) {
handler.setPartitionIdExpression(
EXPRESSION_PARSER.parseExpression("headers['" + BinderHeaders.PARTITION_HEADER + "']"));
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
Assert.notNull(getProcessorFactory(), "processor factory can't be null when create a consumer");
boolean anonymous = !StringUtils.hasText(group);
if (anonymous) {
group = "anonymous." + UUID.randomUUID();
}
EventHubsContainerProperties containerProperties = createContainerProperties(destination, group, properties);
EventHubsMessageListenerContainer listenerContainer = new EventHubsMessageListenerContainer(
getProcessorFactory(), containerProperties);
this.eventHubsMessageListenerContainers.add(listenerContainer);
EventHubsInboundChannelAdapter inboundAdapter;
if (properties.isBatchMode()) {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer, ListenerMode.BATCH);
} else {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer);
}
inboundAdapter.setBeanFactory(getBeanFactory());
String instrumentationId = Instrumentation.buildId(CONSUMER, destination.getName() + "/" + group);
inboundAdapter.setInstrumentationManager(instrumentationManager);
inboundAdapter.setInstrumentationId(instrumentationId);
ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties);
inboundAdapter.setErrorChannel(errorInfrastructure.getErrorChannel());
return inboundAdapter;
}
/**
* Create {@link EventHubsContainerProperties} from the extended {@link EventHubsConsumerProperties}.
* @param destination reference to the consumer destination.
* @param group the consumer group.
* @param properties the consumer properties.
* @return the {@link EventHubsContainerProperties}.
*/
private EventHubsContainerProperties createContainerProperties(
ConsumerDestination destination,
String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
EventHubsContainerProperties containerProperties = new EventHubsContainerProperties();
AzurePropertiesUtils.copyAzureCommonProperties(properties.getExtension(), containerProperties);
ProcessorPropertiesMerger.copyProcessorPropertiesIfNotNull(properties.getExtension(), containerProperties);
containerProperties.setEventHubName(destination.getName());
containerProperties.setConsumerGroup(group);
containerProperties.setCheckpointConfig(properties.getExtension().getCheckpoint());
return containerProperties;
}
@Override
public EventHubsConsumerProperties getExtendedConsumerProperties(String destination) {
return this.bindingProperties.getExtendedConsumerProperties(destination);
}
@Override
public EventHubsProducerProperties getExtendedProducerProperties(String destination) {
return this.bindingProperties.getExtendedProducerProperties(destination);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
/**
* Set binding properties.
*
* @param bindingProperties the binding properties
*/
public void setBindingProperties(EventHubsExtendedBindingProperties bindingProperties) {
this.bindingProperties = bindingProperties;
}
private PropertiesSupplier<String, ProducerProperties> getProducerPropertiesSupplier() {
return key -> {
if (this.extendedProducerPropertiesMap.containsKey(key)) {
EventHubsProducerProperties producerProperties = this.extendedProducerPropertiesMap.get(key)
.getExtension();
producerProperties.setEventHubName(key);
return producerProperties;
} else {
LOGGER.debug("Can't find extended properties for {}", key);
return null;
}
};
}
private EventHubsTemplate getEventHubTemplate() {
if (this.eventHubsTemplate == null) {
DefaultEventHubsNamespaceProducerFactory factory = new DefaultEventHubsNamespaceProducerFactory(
this.namespaceProperties, getProducerPropertiesSupplier());
producerFactoryCustomizers.forEach(customizer -> customizer.customize(factory));
factory.addListener((name, producerAsyncClient) -> {
DefaultInstrumentation instrumentation = new DefaultInstrumentation(name, PRODUCER);
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
this.eventHubsTemplate = new EventHubsTemplate(factory);
}
return this.eventHubsTemplate;
}
private EventHubsProcessorFactory getProcessorFactory() {
if (this.processorFactory == null) {
this.processorFactory = new DefaultEventHubsNamespaceProcessorFactory(
this.checkpointStore, this.namespaceProperties);
processorFactoryCustomizers.forEach(customizer -> customizer.customize(processorFactory));
processorFactory.addListener((name, consumerGroup, processorClient) -> {
String instrumentationName = name + "/" + consumerGroup;
Instrumentation instrumentation = new EventHubsProcessorInstrumentation(instrumentationName, CONSUMER, Duration.ofMinutes(2));
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
}
return this.processorFactory;
}
/**
* Set namespace properties.
*
* @param namespaceProperties the namespace properties
*/
public void setNamespaceProperties(NamespaceProperties namespaceProperties) {
this.namespaceProperties = namespaceProperties;
}
/**
* Set checkpoint store.
*
* @param checkpointStore the checkpoint store
*/
public void setCheckpointStore(CheckpointStore checkpointStore) {
this.checkpointStore = checkpointStore;
}
/**
* Get instrumentation manager.
*
* @return instrumentationManager the instrumentation manager
* @see InstrumentationManager
*/
InstrumentationManager getInstrumentationManager() {
return instrumentationManager;
}
/**
* Add a producer factory customizer.
*
* @param producerFactoryCustomizer The producer factory customizer to add.
*/
/**
* Add a processor factory customizer.
*
* @param processorFactoryCustomizer The processor factory customizer to add.
*/
public void addProcessorFactoryCustomizer(EventHubsProcessorFactoryCustomizer processorFactoryCustomizer) {
if (processorFactoryCustomizer != null) {
this.processorFactoryCustomizers.add(processorFactoryCustomizer);
}
}
} | class EventHubsMessageChannelBinder extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<EventHubsConsumerProperties>, ExtendedProducerProperties<EventHubsProducerProperties>, EventHubsChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, EventHubsConsumerProperties, EventHubsProducerProperties> {
private static final Logger LOGGER = LoggerFactory.getLogger(EventHubsMessageChannelBinder.class);
private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
private NamespaceProperties namespaceProperties;
private EventHubsTemplate eventHubsTemplate;
private CheckpointStore checkpointStore;
private DefaultEventHubsNamespaceProcessorFactory processorFactory;
private final List<EventHubsMessageListenerContainer> eventHubsMessageListenerContainers = new ArrayList<>();
private final InstrumentationManager instrumentationManager = new DefaultInstrumentationManager();
private EventHubsExtendedBindingProperties bindingProperties = new EventHubsExtendedBindingProperties();
private final Map<String, ExtendedProducerProperties<EventHubsProducerProperties>>
extendedProducerPropertiesMap = new ConcurrentHashMap<>();
private final List<EventHubsProducerFactoryCustomizer> producerFactoryCustomizers = new ArrayList<>();
private final List<EventHubsProcessorFactoryCustomizer> processorFactoryCustomizers = new ArrayList<>();
/**
* Construct a {@link EventHubsMessageChannelBinder} with the specified headers to embed and {@link EventHubsChannelProvisioner}.
*
* @param headersToEmbed the headers to embed
* @param provisioningProvider the provisioning provider
*/
public EventHubsMessageChannelBinder(String[] headersToEmbed, EventHubsChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(
ProducerDestination destination,
ExtendedProducerProperties<EventHubsProducerProperties> producerProperties,
MessageChannel errorChannel) {
extendedProducerPropertiesMap.put(destination.getName(), producerProperties);
Assert.notNull(getEventHubTemplate(), "eventHubsTemplate can't be null when create a producer");
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), this.eventHubsTemplate);
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout().toMillis());
handler.setSendFailureChannel(errorChannel);
String instrumentationId = Instrumentation.buildId(PRODUCER, destination.getName());
handler.setSendCallback(new InstrumentationSendCallback(instrumentationId, instrumentationManager));
if (producerProperties.isPartitioned()) {
handler.setPartitionIdExpression(
EXPRESSION_PARSER.parseExpression("headers['" + BinderHeaders.PARTITION_HEADER + "']"));
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
Assert.notNull(getProcessorFactory(), "processor factory can't be null when create a consumer");
boolean anonymous = !StringUtils.hasText(group);
if (anonymous) {
group = "anonymous." + UUID.randomUUID();
}
EventHubsContainerProperties containerProperties = createContainerProperties(destination, group, properties);
EventHubsMessageListenerContainer listenerContainer = new EventHubsMessageListenerContainer(
getProcessorFactory(), containerProperties);
this.eventHubsMessageListenerContainers.add(listenerContainer);
EventHubsInboundChannelAdapter inboundAdapter;
if (properties.isBatchMode()) {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer, ListenerMode.BATCH);
} else {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer);
}
inboundAdapter.setBeanFactory(getBeanFactory());
String instrumentationId = Instrumentation.buildId(CONSUMER, destination.getName() + "/" + group);
inboundAdapter.setInstrumentationManager(instrumentationManager);
inboundAdapter.setInstrumentationId(instrumentationId);
ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties);
inboundAdapter.setErrorChannel(errorInfrastructure.getErrorChannel());
return inboundAdapter;
}
/**
* Create {@link EventHubsContainerProperties} from the extended {@link EventHubsConsumerProperties}.
* @param destination reference to the consumer destination.
* @param group the consumer group.
* @param properties the consumer properties.
* @return the {@link EventHubsContainerProperties}.
*/
private EventHubsContainerProperties createContainerProperties(
ConsumerDestination destination,
String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
EventHubsContainerProperties containerProperties = new EventHubsContainerProperties();
AzurePropertiesUtils.copyAzureCommonProperties(properties.getExtension(), containerProperties);
ProcessorPropertiesMerger.copyProcessorPropertiesIfNotNull(properties.getExtension(), containerProperties);
containerProperties.setEventHubName(destination.getName());
containerProperties.setConsumerGroup(group);
containerProperties.setCheckpointConfig(properties.getExtension().getCheckpoint());
return containerProperties;
}
@Override
public EventHubsConsumerProperties getExtendedConsumerProperties(String destination) {
return this.bindingProperties.getExtendedConsumerProperties(destination);
}
@Override
public EventHubsProducerProperties getExtendedProducerProperties(String destination) {
return this.bindingProperties.getExtendedProducerProperties(destination);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
/**
* Set binding properties.
*
* @param bindingProperties the binding properties
*/
public void setBindingProperties(EventHubsExtendedBindingProperties bindingProperties) {
this.bindingProperties = bindingProperties;
}
private PropertiesSupplier<String, ProducerProperties> getProducerPropertiesSupplier() {
return key -> {
if (this.extendedProducerPropertiesMap.containsKey(key)) {
EventHubsProducerProperties producerProperties = this.extendedProducerPropertiesMap.get(key)
.getExtension();
producerProperties.setEventHubName(key);
return producerProperties;
} else {
LOGGER.debug("Can't find extended properties for {}", key);
return null;
}
};
}
private EventHubsTemplate getEventHubTemplate() {
if (this.eventHubsTemplate == null) {
DefaultEventHubsNamespaceProducerFactory factory = new DefaultEventHubsNamespaceProducerFactory(
this.namespaceProperties, getProducerPropertiesSupplier());
producerFactoryCustomizers.forEach(customizer -> customizer.customize(factory));
factory.addListener((name, producerAsyncClient) -> {
DefaultInstrumentation instrumentation = new DefaultInstrumentation(name, PRODUCER);
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
this.eventHubsTemplate = new EventHubsTemplate(factory);
}
return this.eventHubsTemplate;
}
private EventHubsProcessorFactory getProcessorFactory() {
if (this.processorFactory == null) {
this.processorFactory = new DefaultEventHubsNamespaceProcessorFactory(
this.checkpointStore, this.namespaceProperties);
processorFactoryCustomizers.forEach(customizer -> customizer.customize(processorFactory));
processorFactory.addListener((name, consumerGroup, processorClient) -> {
String instrumentationName = name + "/" + consumerGroup;
Instrumentation instrumentation = new EventHubsProcessorInstrumentation(instrumentationName, CONSUMER, Duration.ofMinutes(2));
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
}
return this.processorFactory;
}
/**
* Set namespace properties.
*
* @param namespaceProperties the namespace properties
*/
public void setNamespaceProperties(NamespaceProperties namespaceProperties) {
this.namespaceProperties = namespaceProperties;
}
/**
* Set checkpoint store.
*
* @param checkpointStore the checkpoint store
*/
public void setCheckpointStore(CheckpointStore checkpointStore) {
this.checkpointStore = checkpointStore;
}
/**
* Get instrumentation manager.
*
* @return instrumentationManager the instrumentation manager
* @see InstrumentationManager
*/
InstrumentationManager getInstrumentationManager() {
return instrumentationManager;
}
/**
* Add a producer factory customizer.
*
* @param producerFactoryCustomizer The producer factory customizer to add.
*/
/**
* Add a processor factory customizer.
*
* @param processorFactoryCustomizer The processor factory customizer to add.
*/
public void addProcessorFactoryCustomizer(EventHubsProcessorFactoryCustomizer processorFactoryCustomizer) {
if (processorFactoryCustomizer != null) {
this.processorFactoryCustomizers.add(processorFactoryCustomizer);
}
}
} |
not for now | public void addProducerFactoryCustomizer(EventHubsProducerFactoryCustomizer producerFactoryCustomizer) {
if (producerFactoryCustomizer != null) {
this.producerFactoryCustomizers.add(producerFactoryCustomizer);
}
} | this.producerFactoryCustomizers.add(producerFactoryCustomizer); | public void addProducerFactoryCustomizer(EventHubsProducerFactoryCustomizer producerFactoryCustomizer) {
if (producerFactoryCustomizer != null) {
this.producerFactoryCustomizers.add(producerFactoryCustomizer);
}
} | class EventHubsMessageChannelBinder extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<EventHubsConsumerProperties>, ExtendedProducerProperties<EventHubsProducerProperties>, EventHubsChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, EventHubsConsumerProperties, EventHubsProducerProperties> {
private static final Logger LOGGER = LoggerFactory.getLogger(EventHubsMessageChannelBinder.class);
private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
private NamespaceProperties namespaceProperties;
private EventHubsTemplate eventHubsTemplate;
private CheckpointStore checkpointStore;
private DefaultEventHubsNamespaceProcessorFactory processorFactory;
private final List<EventHubsMessageListenerContainer> eventHubsMessageListenerContainers = new ArrayList<>();
private final InstrumentationManager instrumentationManager = new DefaultInstrumentationManager();
private EventHubsExtendedBindingProperties bindingProperties = new EventHubsExtendedBindingProperties();
private final Map<String, ExtendedProducerProperties<EventHubsProducerProperties>>
extendedProducerPropertiesMap = new ConcurrentHashMap<>();
private final List<EventHubsProducerFactoryCustomizer> producerFactoryCustomizers = new ArrayList<>();
private final List<EventHubsProcessorFactoryCustomizer> processorFactoryCustomizers = new ArrayList<>();
/**
* Construct a {@link EventHubsMessageChannelBinder} with the specified headers to embed and {@link EventHubsChannelProvisioner}.
*
* @param headersToEmbed the headers to embed
* @param provisioningProvider the provisioning provider
*/
public EventHubsMessageChannelBinder(String[] headersToEmbed, EventHubsChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(
ProducerDestination destination,
ExtendedProducerProperties<EventHubsProducerProperties> producerProperties,
MessageChannel errorChannel) {
extendedProducerPropertiesMap.put(destination.getName(), producerProperties);
Assert.notNull(getEventHubTemplate(), "eventHubsTemplate can't be null when create a producer");
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), this.eventHubsTemplate);
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout().toMillis());
handler.setSendFailureChannel(errorChannel);
String instrumentationId = Instrumentation.buildId(PRODUCER, destination.getName());
handler.setSendCallback(new InstrumentationSendCallback(instrumentationId, instrumentationManager));
if (producerProperties.isPartitioned()) {
handler.setPartitionIdExpression(
EXPRESSION_PARSER.parseExpression("headers['" + BinderHeaders.PARTITION_HEADER + "']"));
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
Assert.notNull(getProcessorFactory(), "processor factory can't be null when create a consumer");
boolean anonymous = !StringUtils.hasText(group);
if (anonymous) {
group = "anonymous." + UUID.randomUUID();
}
EventHubsContainerProperties containerProperties = createContainerProperties(destination, group, properties);
EventHubsMessageListenerContainer listenerContainer = new EventHubsMessageListenerContainer(
getProcessorFactory(), containerProperties);
this.eventHubsMessageListenerContainers.add(listenerContainer);
EventHubsInboundChannelAdapter inboundAdapter;
if (properties.isBatchMode()) {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer, ListenerMode.BATCH);
} else {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer);
}
inboundAdapter.setBeanFactory(getBeanFactory());
String instrumentationId = Instrumentation.buildId(CONSUMER, destination.getName() + "/" + group);
inboundAdapter.setInstrumentationManager(instrumentationManager);
inboundAdapter.setInstrumentationId(instrumentationId);
ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties);
inboundAdapter.setErrorChannel(errorInfrastructure.getErrorChannel());
return inboundAdapter;
}
/**
* Create {@link EventHubsContainerProperties} from the extended {@link EventHubsConsumerProperties}.
* @param destination reference to the consumer destination.
* @param group the consumer group.
* @param properties the consumer properties.
* @return the {@link EventHubsContainerProperties}.
*/
private EventHubsContainerProperties createContainerProperties(
ConsumerDestination destination,
String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
EventHubsContainerProperties containerProperties = new EventHubsContainerProperties();
AzurePropertiesUtils.copyAzureCommonProperties(properties.getExtension(), containerProperties);
ProcessorPropertiesMerger.copyProcessorPropertiesIfNotNull(properties.getExtension(), containerProperties);
containerProperties.setEventHubName(destination.getName());
containerProperties.setConsumerGroup(group);
containerProperties.setCheckpointConfig(properties.getExtension().getCheckpoint());
return containerProperties;
}
@Override
public EventHubsConsumerProperties getExtendedConsumerProperties(String destination) {
return this.bindingProperties.getExtendedConsumerProperties(destination);
}
@Override
public EventHubsProducerProperties getExtendedProducerProperties(String destination) {
return this.bindingProperties.getExtendedProducerProperties(destination);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
/**
* Set binding properties.
*
* @param bindingProperties the binding properties
*/
public void setBindingProperties(EventHubsExtendedBindingProperties bindingProperties) {
this.bindingProperties = bindingProperties;
}
private PropertiesSupplier<String, ProducerProperties> getProducerPropertiesSupplier() {
return key -> {
if (this.extendedProducerPropertiesMap.containsKey(key)) {
EventHubsProducerProperties producerProperties = this.extendedProducerPropertiesMap.get(key)
.getExtension();
producerProperties.setEventHubName(key);
return producerProperties;
} else {
LOGGER.debug("Can't find extended properties for {}", key);
return null;
}
};
}
private EventHubsTemplate getEventHubTemplate() {
if (this.eventHubsTemplate == null) {
DefaultEventHubsNamespaceProducerFactory factory = new DefaultEventHubsNamespaceProducerFactory(
this.namespaceProperties, getProducerPropertiesSupplier());
producerFactoryCustomizers.forEach(customizer -> customizer.customize(factory));
factory.addListener((name, producerAsyncClient) -> {
DefaultInstrumentation instrumentation = new DefaultInstrumentation(name, PRODUCER);
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
this.eventHubsTemplate = new EventHubsTemplate(factory);
}
return this.eventHubsTemplate;
}
private EventHubsProcessorFactory getProcessorFactory() {
if (this.processorFactory == null) {
this.processorFactory = new DefaultEventHubsNamespaceProcessorFactory(
this.checkpointStore, this.namespaceProperties);
processorFactoryCustomizers.forEach(customizer -> customizer.customize(processorFactory));
processorFactory.addListener((name, consumerGroup, processorClient) -> {
String instrumentationName = name + "/" + consumerGroup;
Instrumentation instrumentation = new EventHubsProcessorInstrumentation(instrumentationName, CONSUMER, Duration.ofMinutes(2));
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
}
return this.processorFactory;
}
/**
* Set namespace properties.
*
* @param namespaceProperties the namespace properties
*/
public void setNamespaceProperties(NamespaceProperties namespaceProperties) {
this.namespaceProperties = namespaceProperties;
}
/**
* Set checkpoint store.
*
* @param checkpointStore the checkpoint store
*/
public void setCheckpointStore(CheckpointStore checkpointStore) {
this.checkpointStore = checkpointStore;
}
/**
* Get instrumentation manager.
*
* @return instrumentationManager the instrumentation manager
* @see InstrumentationManager
*/
InstrumentationManager getInstrumentationManager() {
return instrumentationManager;
}
/**
* Add a producer factory customizer.
*
* @param producerFactoryCustomizer The producer factory customizer to add.
*/
/**
* Add a processor factory customizer.
*
* @param processorFactoryCustomizer The processor factory customizer to add.
*/
public void addProcessorFactoryCustomizer(EventHubsProcessorFactoryCustomizer processorFactoryCustomizer) {
if (processorFactoryCustomizer != null) {
this.processorFactoryCustomizers.add(processorFactoryCustomizer);
}
}
} | class EventHubsMessageChannelBinder extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<EventHubsConsumerProperties>, ExtendedProducerProperties<EventHubsProducerProperties>, EventHubsChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, EventHubsConsumerProperties, EventHubsProducerProperties> {
private static final Logger LOGGER = LoggerFactory.getLogger(EventHubsMessageChannelBinder.class);
private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
private NamespaceProperties namespaceProperties;
private EventHubsTemplate eventHubsTemplate;
private CheckpointStore checkpointStore;
private DefaultEventHubsNamespaceProcessorFactory processorFactory;
private final List<EventHubsMessageListenerContainer> eventHubsMessageListenerContainers = new ArrayList<>();
private final InstrumentationManager instrumentationManager = new DefaultInstrumentationManager();
private EventHubsExtendedBindingProperties bindingProperties = new EventHubsExtendedBindingProperties();
private final Map<String, ExtendedProducerProperties<EventHubsProducerProperties>>
extendedProducerPropertiesMap = new ConcurrentHashMap<>();
private final List<EventHubsProducerFactoryCustomizer> producerFactoryCustomizers = new ArrayList<>();
private final List<EventHubsProcessorFactoryCustomizer> processorFactoryCustomizers = new ArrayList<>();
/**
* Construct a {@link EventHubsMessageChannelBinder} with the specified headers to embed and {@link EventHubsChannelProvisioner}.
*
* @param headersToEmbed the headers to embed
* @param provisioningProvider the provisioning provider
*/
public EventHubsMessageChannelBinder(String[] headersToEmbed, EventHubsChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(
ProducerDestination destination,
ExtendedProducerProperties<EventHubsProducerProperties> producerProperties,
MessageChannel errorChannel) {
extendedProducerPropertiesMap.put(destination.getName(), producerProperties);
Assert.notNull(getEventHubTemplate(), "eventHubsTemplate can't be null when create a producer");
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), this.eventHubsTemplate);
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout().toMillis());
handler.setSendFailureChannel(errorChannel);
String instrumentationId = Instrumentation.buildId(PRODUCER, destination.getName());
handler.setSendCallback(new InstrumentationSendCallback(instrumentationId, instrumentationManager));
if (producerProperties.isPartitioned()) {
handler.setPartitionIdExpression(
EXPRESSION_PARSER.parseExpression("headers['" + BinderHeaders.PARTITION_HEADER + "']"));
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
Assert.notNull(getProcessorFactory(), "processor factory can't be null when create a consumer");
boolean anonymous = !StringUtils.hasText(group);
if (anonymous) {
group = "anonymous." + UUID.randomUUID();
}
EventHubsContainerProperties containerProperties = createContainerProperties(destination, group, properties);
EventHubsMessageListenerContainer listenerContainer = new EventHubsMessageListenerContainer(
getProcessorFactory(), containerProperties);
this.eventHubsMessageListenerContainers.add(listenerContainer);
EventHubsInboundChannelAdapter inboundAdapter;
if (properties.isBatchMode()) {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer, ListenerMode.BATCH);
} else {
inboundAdapter = new EventHubsInboundChannelAdapter(listenerContainer);
}
inboundAdapter.setBeanFactory(getBeanFactory());
String instrumentationId = Instrumentation.buildId(CONSUMER, destination.getName() + "/" + group);
inboundAdapter.setInstrumentationManager(instrumentationManager);
inboundAdapter.setInstrumentationId(instrumentationId);
ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties);
inboundAdapter.setErrorChannel(errorInfrastructure.getErrorChannel());
return inboundAdapter;
}
/**
* Create {@link EventHubsContainerProperties} from the extended {@link EventHubsConsumerProperties}.
* @param destination reference to the consumer destination.
* @param group the consumer group.
* @param properties the consumer properties.
* @return the {@link EventHubsContainerProperties}.
*/
private EventHubsContainerProperties createContainerProperties(
ConsumerDestination destination,
String group,
ExtendedConsumerProperties<EventHubsConsumerProperties> properties) {
EventHubsContainerProperties containerProperties = new EventHubsContainerProperties();
AzurePropertiesUtils.copyAzureCommonProperties(properties.getExtension(), containerProperties);
ProcessorPropertiesMerger.copyProcessorPropertiesIfNotNull(properties.getExtension(), containerProperties);
containerProperties.setEventHubName(destination.getName());
containerProperties.setConsumerGroup(group);
containerProperties.setCheckpointConfig(properties.getExtension().getCheckpoint());
return containerProperties;
}
@Override
public EventHubsConsumerProperties getExtendedConsumerProperties(String destination) {
return this.bindingProperties.getExtendedConsumerProperties(destination);
}
@Override
public EventHubsProducerProperties getExtendedProducerProperties(String destination) {
return this.bindingProperties.getExtendedProducerProperties(destination);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
/**
* Set binding properties.
*
* @param bindingProperties the binding properties
*/
public void setBindingProperties(EventHubsExtendedBindingProperties bindingProperties) {
this.bindingProperties = bindingProperties;
}
private PropertiesSupplier<String, ProducerProperties> getProducerPropertiesSupplier() {
return key -> {
if (this.extendedProducerPropertiesMap.containsKey(key)) {
EventHubsProducerProperties producerProperties = this.extendedProducerPropertiesMap.get(key)
.getExtension();
producerProperties.setEventHubName(key);
return producerProperties;
} else {
LOGGER.debug("Can't find extended properties for {}", key);
return null;
}
};
}
private EventHubsTemplate getEventHubTemplate() {
if (this.eventHubsTemplate == null) {
DefaultEventHubsNamespaceProducerFactory factory = new DefaultEventHubsNamespaceProducerFactory(
this.namespaceProperties, getProducerPropertiesSupplier());
producerFactoryCustomizers.forEach(customizer -> customizer.customize(factory));
factory.addListener((name, producerAsyncClient) -> {
DefaultInstrumentation instrumentation = new DefaultInstrumentation(name, PRODUCER);
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
this.eventHubsTemplate = new EventHubsTemplate(factory);
}
return this.eventHubsTemplate;
}
private EventHubsProcessorFactory getProcessorFactory() {
if (this.processorFactory == null) {
this.processorFactory = new DefaultEventHubsNamespaceProcessorFactory(
this.checkpointStore, this.namespaceProperties);
processorFactoryCustomizers.forEach(customizer -> customizer.customize(processorFactory));
processorFactory.addListener((name, consumerGroup, processorClient) -> {
String instrumentationName = name + "/" + consumerGroup;
Instrumentation instrumentation = new EventHubsProcessorInstrumentation(instrumentationName, CONSUMER, Duration.ofMinutes(2));
instrumentation.setStatus(Instrumentation.Status.UP);
instrumentationManager.addHealthInstrumentation(instrumentation);
});
}
return this.processorFactory;
}
/**
* Set namespace properties.
*
* @param namespaceProperties the namespace properties
*/
public void setNamespaceProperties(NamespaceProperties namespaceProperties) {
this.namespaceProperties = namespaceProperties;
}
/**
* Set checkpoint store.
*
* @param checkpointStore the checkpoint store
*/
public void setCheckpointStore(CheckpointStore checkpointStore) {
this.checkpointStore = checkpointStore;
}
/**
* Get instrumentation manager.
*
* @return instrumentationManager the instrumentation manager
* @see InstrumentationManager
*/
InstrumentationManager getInstrumentationManager() {
return instrumentationManager;
}
/**
* Add a producer factory customizer.
*
* @param producerFactoryCustomizer The producer factory customizer to add.
*/
/**
* Add a processor factory customizer.
*
* @param processorFactoryCustomizer The processor factory customizer to add.
*/
public void addProcessorFactoryCustomizer(EventHubsProcessorFactoryCustomizer processorFactoryCustomizer) {
if (processorFactoryCustomizer != null) {
this.processorFactoryCustomizers.add(processorFactoryCustomizer);
}
}
} |
Is there any reason that we only use `sqlExpression` in hashCode, but equals contains all fields (nullable field seems acceptable for `Objects.hash`)? | public int hashCode() {
return sqlExpression.hashCode();
} | return sqlExpression.hashCode(); | public int hashCode() {
return sqlExpression.hashCode();
} | class SqlRuleFilter extends RuleFilter {
private final Map<String, Object> properties = new HashMap<>();
private final String sqlExpression;
private final String compatibilityLevel;
private final Boolean requiresPreprocessing;
/**
* Creates a new instance with the given SQL expression.
*
* @param sqlExpression SQL expression for the filter.
*
* @throws NullPointerException if {@code sqlExpression} is null.
* @throws IllegalArgumentException if {@code sqlExpression} is an empty string.
*/
public SqlRuleFilter(String sqlExpression) {
final ClientLogger logger = new ClientLogger(SqlRuleFilter.class);
if (sqlExpression == null) {
throw logger.logExceptionAsError(new NullPointerException("'sqlExpression' cannot be null."));
} else if (sqlExpression.isEmpty()) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'sqlExpression' cannot be an empty string."));
}
this.sqlExpression = sqlExpression;
this.compatibilityLevel = null;
this.requiresPreprocessing = null;
}
/**
* Package private constructor for creating a model deserialised from the service.
*
* @param sqlExpression SQL expression for the filter.
* @param compatibilityLevel The compatibility level.
* @param requiresPreprocessing Whether or not it requires preprocessing
*/
SqlRuleFilter(String sqlExpression, String compatibilityLevel, Boolean requiresPreprocessing) {
this.sqlExpression = sqlExpression;
this.compatibilityLevel = compatibilityLevel;
this.requiresPreprocessing = requiresPreprocessing;
}
/**
* Gets the compatibility level.
*
* @return The compatibility level.
*/
String getCompatibilityLevel() {
return compatibilityLevel;
}
/**
* Gets whether or not requires preprocessing.
*
* @return Whether or not requires preprocessing.
*/
Boolean isPreprocessingRequired() {
return requiresPreprocessing;
}
/**
* Gets the value of a filter expression. Allowed types: string, int, long, bool, double
*
* @return Gets the value of a filter expression.
*/
public Map<String, Object> getParameters() {
return properties;
}
/**
* Gets the SQL expression.
*
* @return The SQL expression.
*/
public String getSqlExpression() {
return sqlExpression;
}
/**
* Converts the value of the current instance to its equivalent string representation.
*
* @return A string representation of the current instance.
*/
@Override
public String toString() {
return String.format("SqlRuleFilter: %s", sqlExpression);
}
/**
* Compares this RuleFilter to the specified object. The result is true if and only if the argument is not null
* and is a SqlRuleFilter object that with the same parameters as this object.
*
* @param other - the object to which the current SqlRuleFilter should be compared.
* @return True, if the passed object is a SqlRuleFilter with the same parameter values, False otherwise.
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof SqlRuleFilter)) {
return false;
}
SqlRuleFilter that = (SqlRuleFilter) other;
return sqlExpression.equals(that.sqlExpression)
&& Objects.equals(compatibilityLevel, that.compatibilityLevel)
&& Objects.equals(requiresPreprocessing, that.requiresPreprocessing)
&& Objects.equals(properties, that.properties);
}
/**
* Returns a hash code for this SqlRuleFilter, which is the hashcode for the SqlExpression.
*
* @return a hash code value for this object.
*/
@Override
} | class SqlRuleFilter extends RuleFilter {
private final Map<String, Object> properties = new HashMap<>();
private final String sqlExpression;
private final String compatibilityLevel;
private final Boolean requiresPreprocessing;
/**
* Creates a new instance with the given SQL expression.
*
* @param sqlExpression SQL expression for the filter.
*
* @throws NullPointerException if {@code sqlExpression} is null.
* @throws IllegalArgumentException if {@code sqlExpression} is an empty string.
*/
public SqlRuleFilter(String sqlExpression) {
final ClientLogger logger = new ClientLogger(SqlRuleFilter.class);
if (sqlExpression == null) {
throw logger.logExceptionAsError(new NullPointerException("'sqlExpression' cannot be null."));
} else if (sqlExpression.isEmpty()) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'sqlExpression' cannot be an empty string."));
}
this.sqlExpression = sqlExpression;
this.compatibilityLevel = null;
this.requiresPreprocessing = null;
}
/**
* Package private constructor for creating a model deserialised from the service.
*
* @param sqlExpression SQL expression for the filter.
* @param compatibilityLevel The compatibility level.
* @param requiresPreprocessing Whether or not it requires preprocessing
*/
SqlRuleFilter(String sqlExpression, String compatibilityLevel, Boolean requiresPreprocessing) {
this.sqlExpression = sqlExpression;
this.compatibilityLevel = compatibilityLevel;
this.requiresPreprocessing = requiresPreprocessing;
}
/**
* Gets the compatibility level.
*
* @return The compatibility level.
*/
String getCompatibilityLevel() {
return compatibilityLevel;
}
/**
* Gets whether or not requires preprocessing.
*
* @return Whether or not requires preprocessing.
*/
Boolean isPreprocessingRequired() {
return requiresPreprocessing;
}
/**
* Gets the value of a filter expression. Allowed types: string, int, long, bool, double
*
* @return Gets the value of a filter expression.
*/
public Map<String, Object> getParameters() {
return properties;
}
/**
* Gets the SQL expression.
*
* @return The SQL expression.
*/
public String getSqlExpression() {
return sqlExpression;
}
/**
* Converts the value of the current instance to its equivalent string representation.
*
* @return A string representation of the current instance.
*/
@Override
public String toString() {
return String.format("SqlRuleFilter: %s", sqlExpression);
}
/**
* Compares this RuleFilter to the specified object. The result is true if and only if the argument is not null
* and is a SqlRuleFilter object that with the same parameters as this object.
*
* @param other - the object to which the current SqlRuleFilter should be compared.
* @return True, if the passed object is a SqlRuleFilter with the same parameter values, False otherwise.
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof SqlRuleFilter)) {
return false;
}
SqlRuleFilter that = (SqlRuleFilter) other;
return sqlExpression.equals(that.sqlExpression)
&& Objects.equals(compatibilityLevel, that.compatibilityLevel)
&& Objects.equals(requiresPreprocessing, that.requiresPreprocessing)
&& Objects.equals(properties, that.properties);
}
/**
* Returns a hash code for this SqlRuleFilter, which is the hashcode for the SqlExpression.
*
* @return a hash code value for this object.
*/
@Override
} |
In my original pull request, I did hash the three attributes. My submission implements this differently  | public int hashCode() {
return sqlExpression.hashCode();
} | return sqlExpression.hashCode(); | public int hashCode() {
return sqlExpression.hashCode();
} | class SqlRuleFilter extends RuleFilter {
private final Map<String, Object> properties = new HashMap<>();
private final String sqlExpression;
private final String compatibilityLevel;
private final Boolean requiresPreprocessing;
/**
* Creates a new instance with the given SQL expression.
*
* @param sqlExpression SQL expression for the filter.
*
* @throws NullPointerException if {@code sqlExpression} is null.
* @throws IllegalArgumentException if {@code sqlExpression} is an empty string.
*/
public SqlRuleFilter(String sqlExpression) {
final ClientLogger logger = new ClientLogger(SqlRuleFilter.class);
if (sqlExpression == null) {
throw logger.logExceptionAsError(new NullPointerException("'sqlExpression' cannot be null."));
} else if (sqlExpression.isEmpty()) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'sqlExpression' cannot be an empty string."));
}
this.sqlExpression = sqlExpression;
this.compatibilityLevel = null;
this.requiresPreprocessing = null;
}
/**
* Package private constructor for creating a model deserialised from the service.
*
* @param sqlExpression SQL expression for the filter.
* @param compatibilityLevel The compatibility level.
* @param requiresPreprocessing Whether or not it requires preprocessing
*/
SqlRuleFilter(String sqlExpression, String compatibilityLevel, Boolean requiresPreprocessing) {
this.sqlExpression = sqlExpression;
this.compatibilityLevel = compatibilityLevel;
this.requiresPreprocessing = requiresPreprocessing;
}
/**
* Gets the compatibility level.
*
* @return The compatibility level.
*/
String getCompatibilityLevel() {
return compatibilityLevel;
}
/**
* Gets whether or not requires preprocessing.
*
* @return Whether or not requires preprocessing.
*/
Boolean isPreprocessingRequired() {
return requiresPreprocessing;
}
/**
* Gets the value of a filter expression. Allowed types: string, int, long, bool, double
*
* @return Gets the value of a filter expression.
*/
public Map<String, Object> getParameters() {
return properties;
}
/**
* Gets the SQL expression.
*
* @return The SQL expression.
*/
public String getSqlExpression() {
return sqlExpression;
}
/**
* Converts the value of the current instance to its equivalent string representation.
*
* @return A string representation of the current instance.
*/
@Override
public String toString() {
return String.format("SqlRuleFilter: %s", sqlExpression);
}
/**
* Compares this RuleFilter to the specified object. The result is true if and only if the argument is not null
* and is a SqlRuleFilter object that with the same parameters as this object.
*
* @param other - the object to which the current SqlRuleFilter should be compared.
* @return True, if the passed object is a SqlRuleFilter with the same parameter values, False otherwise.
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof SqlRuleFilter)) {
return false;
}
SqlRuleFilter that = (SqlRuleFilter) other;
return sqlExpression.equals(that.sqlExpression)
&& Objects.equals(compatibilityLevel, that.compatibilityLevel)
&& Objects.equals(requiresPreprocessing, that.requiresPreprocessing)
&& Objects.equals(properties, that.properties);
}
/**
* Returns a hash code for this SqlRuleFilter, which is the hashcode for the SqlExpression.
*
* @return a hash code value for this object.
*/
@Override
} | class SqlRuleFilter extends RuleFilter {
private final Map<String, Object> properties = new HashMap<>();
private final String sqlExpression;
private final String compatibilityLevel;
private final Boolean requiresPreprocessing;
/**
* Creates a new instance with the given SQL expression.
*
* @param sqlExpression SQL expression for the filter.
*
* @throws NullPointerException if {@code sqlExpression} is null.
* @throws IllegalArgumentException if {@code sqlExpression} is an empty string.
*/
public SqlRuleFilter(String sqlExpression) {
final ClientLogger logger = new ClientLogger(SqlRuleFilter.class);
if (sqlExpression == null) {
throw logger.logExceptionAsError(new NullPointerException("'sqlExpression' cannot be null."));
} else if (sqlExpression.isEmpty()) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'sqlExpression' cannot be an empty string."));
}
this.sqlExpression = sqlExpression;
this.compatibilityLevel = null;
this.requiresPreprocessing = null;
}
/**
* Package private constructor for creating a model deserialised from the service.
*
* @param sqlExpression SQL expression for the filter.
* @param compatibilityLevel The compatibility level.
* @param requiresPreprocessing Whether or not it requires preprocessing
*/
SqlRuleFilter(String sqlExpression, String compatibilityLevel, Boolean requiresPreprocessing) {
this.sqlExpression = sqlExpression;
this.compatibilityLevel = compatibilityLevel;
this.requiresPreprocessing = requiresPreprocessing;
}
/**
* Gets the compatibility level.
*
* @return The compatibility level.
*/
String getCompatibilityLevel() {
return compatibilityLevel;
}
/**
* Gets whether or not requires preprocessing.
*
* @return Whether or not requires preprocessing.
*/
Boolean isPreprocessingRequired() {
return requiresPreprocessing;
}
/**
* Gets the value of a filter expression. Allowed types: string, int, long, bool, double
*
* @return Gets the value of a filter expression.
*/
public Map<String, Object> getParameters() {
return properties;
}
/**
* Gets the SQL expression.
*
* @return The SQL expression.
*/
public String getSqlExpression() {
return sqlExpression;
}
/**
* Converts the value of the current instance to its equivalent string representation.
*
* @return A string representation of the current instance.
*/
@Override
public String toString() {
return String.format("SqlRuleFilter: %s", sqlExpression);
}
/**
* Compares this RuleFilter to the specified object. The result is true if and only if the argument is not null
* and is a SqlRuleFilter object that with the same parameters as this object.
*
* @param other - the object to which the current SqlRuleFilter should be compared.
* @return True, if the passed object is a SqlRuleFilter with the same parameter values, False otherwise.
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof SqlRuleFilter)) {
return false;
}
SqlRuleFilter that = (SqlRuleFilter) other;
return sqlExpression.equals(that.sqlExpression)
&& Objects.equals(compatibilityLevel, that.compatibilityLevel)
&& Objects.equals(requiresPreprocessing, that.requiresPreprocessing)
&& Objects.equals(properties, that.properties);
}
/**
* Returns a hash code for this SqlRuleFilter, which is the hashcode for the SqlExpression.
*
* @return a hash code value for this object.
*/
@Override
} |
The idea behind adding just the sql expression into the hashcode here is that sql expression is the important unique identifier of the filter (the only one settable by client), and is sufficient to produce a unique hashcode. Here is the C# code as well, following the same idea - https://github.com/Azure/azure-sdk-for-net/blob/0bda2178d9677f156f80f0793998a6a99edf93e7/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/Rules/SqlRuleFilter.cs#L66 | public int hashCode() {
return sqlExpression.hashCode();
} | return sqlExpression.hashCode(); | public int hashCode() {
return sqlExpression.hashCode();
} | class SqlRuleFilter extends RuleFilter {
private final Map<String, Object> properties = new HashMap<>();
private final String sqlExpression;
private final String compatibilityLevel;
private final Boolean requiresPreprocessing;
/**
* Creates a new instance with the given SQL expression.
*
* @param sqlExpression SQL expression for the filter.
*
* @throws NullPointerException if {@code sqlExpression} is null.
* @throws IllegalArgumentException if {@code sqlExpression} is an empty string.
*/
public SqlRuleFilter(String sqlExpression) {
final ClientLogger logger = new ClientLogger(SqlRuleFilter.class);
if (sqlExpression == null) {
throw logger.logExceptionAsError(new NullPointerException("'sqlExpression' cannot be null."));
} else if (sqlExpression.isEmpty()) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'sqlExpression' cannot be an empty string."));
}
this.sqlExpression = sqlExpression;
this.compatibilityLevel = null;
this.requiresPreprocessing = null;
}
/**
* Package private constructor for creating a model deserialised from the service.
*
* @param sqlExpression SQL expression for the filter.
* @param compatibilityLevel The compatibility level.
* @param requiresPreprocessing Whether or not it requires preprocessing
*/
SqlRuleFilter(String sqlExpression, String compatibilityLevel, Boolean requiresPreprocessing) {
this.sqlExpression = sqlExpression;
this.compatibilityLevel = compatibilityLevel;
this.requiresPreprocessing = requiresPreprocessing;
}
/**
* Gets the compatibility level.
*
* @return The compatibility level.
*/
String getCompatibilityLevel() {
return compatibilityLevel;
}
/**
* Gets whether or not requires preprocessing.
*
* @return Whether or not requires preprocessing.
*/
Boolean isPreprocessingRequired() {
return requiresPreprocessing;
}
/**
* Gets the value of a filter expression. Allowed types: string, int, long, bool, double
*
* @return Gets the value of a filter expression.
*/
public Map<String, Object> getParameters() {
return properties;
}
/**
* Gets the SQL expression.
*
* @return The SQL expression.
*/
public String getSqlExpression() {
return sqlExpression;
}
/**
* Converts the value of the current instance to its equivalent string representation.
*
* @return A string representation of the current instance.
*/
@Override
public String toString() {
return String.format("SqlRuleFilter: %s", sqlExpression);
}
/**
* Compares this RuleFilter to the specified object. The result is true if and only if the argument is not null
* and is a SqlRuleFilter object that with the same parameters as this object.
*
* @param other - the object to which the current SqlRuleFilter should be compared.
* @return True, if the passed object is a SqlRuleFilter with the same parameter values, False otherwise.
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof SqlRuleFilter)) {
return false;
}
SqlRuleFilter that = (SqlRuleFilter) other;
return sqlExpression.equals(that.sqlExpression)
&& Objects.equals(compatibilityLevel, that.compatibilityLevel)
&& Objects.equals(requiresPreprocessing, that.requiresPreprocessing)
&& Objects.equals(properties, that.properties);
}
/**
* Returns a hash code for this SqlRuleFilter, which is the hashcode for the SqlExpression.
*
* @return a hash code value for this object.
*/
@Override
} | class SqlRuleFilter extends RuleFilter {
private final Map<String, Object> properties = new HashMap<>();
private final String sqlExpression;
private final String compatibilityLevel;
private final Boolean requiresPreprocessing;
/**
* Creates a new instance with the given SQL expression.
*
* @param sqlExpression SQL expression for the filter.
*
* @throws NullPointerException if {@code sqlExpression} is null.
* @throws IllegalArgumentException if {@code sqlExpression} is an empty string.
*/
public SqlRuleFilter(String sqlExpression) {
final ClientLogger logger = new ClientLogger(SqlRuleFilter.class);
if (sqlExpression == null) {
throw logger.logExceptionAsError(new NullPointerException("'sqlExpression' cannot be null."));
} else if (sqlExpression.isEmpty()) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'sqlExpression' cannot be an empty string."));
}
this.sqlExpression = sqlExpression;
this.compatibilityLevel = null;
this.requiresPreprocessing = null;
}
/**
* Package private constructor for creating a model deserialised from the service.
*
* @param sqlExpression SQL expression for the filter.
* @param compatibilityLevel The compatibility level.
* @param requiresPreprocessing Whether or not it requires preprocessing
*/
SqlRuleFilter(String sqlExpression, String compatibilityLevel, Boolean requiresPreprocessing) {
this.sqlExpression = sqlExpression;
this.compatibilityLevel = compatibilityLevel;
this.requiresPreprocessing = requiresPreprocessing;
}
/**
* Gets the compatibility level.
*
* @return The compatibility level.
*/
String getCompatibilityLevel() {
return compatibilityLevel;
}
/**
* Gets whether or not requires preprocessing.
*
* @return Whether or not requires preprocessing.
*/
Boolean isPreprocessingRequired() {
return requiresPreprocessing;
}
/**
* Gets the value of a filter expression. Allowed types: string, int, long, bool, double
*
* @return Gets the value of a filter expression.
*/
public Map<String, Object> getParameters() {
return properties;
}
/**
* Gets the SQL expression.
*
* @return The SQL expression.
*/
public String getSqlExpression() {
return sqlExpression;
}
/**
* Converts the value of the current instance to its equivalent string representation.
*
* @return A string representation of the current instance.
*/
@Override
public String toString() {
return String.format("SqlRuleFilter: %s", sqlExpression);
}
/**
* Compares this RuleFilter to the specified object. The result is true if and only if the argument is not null
* and is a SqlRuleFilter object that with the same parameters as this object.
*
* @param other - the object to which the current SqlRuleFilter should be compared.
* @return True, if the passed object is a SqlRuleFilter with the same parameter values, False otherwise.
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof SqlRuleFilter)) {
return false;
}
SqlRuleFilter that = (SqlRuleFilter) other;
return sqlExpression.equals(that.sqlExpression)
&& Objects.equals(compatibilityLevel, that.compatibilityLevel)
&& Objects.equals(requiresPreprocessing, that.requiresPreprocessing)
&& Objects.equals(properties, that.properties);
}
/**
* Returns a hash code for this SqlRuleFilter, which is the hashcode for the SqlExpression.
*
* @return a hash code value for this object.
*/
@Override
} |
It does make sense, that these objects are consistent with the C# implementation. I am trying to reconcile that against the accepted practice that objects that are equal (via the equals method) have the same hashCode. This will still be true, but then we will have objects that are not equal which still have the same hashCode (two SqlExpression filters that have the same sqlExpression but different compatibility levels, for example). The safest path could have the equals and hashCode methods implement using the same attributes. But, this could be splitting hairs. :) More thinking out loud. | public int hashCode() {
return sqlExpression.hashCode();
} | return sqlExpression.hashCode(); | public int hashCode() {
return sqlExpression.hashCode();
} | class SqlRuleFilter extends RuleFilter {
private final Map<String, Object> properties = new HashMap<>();
private final String sqlExpression;
private final String compatibilityLevel;
private final Boolean requiresPreprocessing;
/**
* Creates a new instance with the given SQL expression.
*
* @param sqlExpression SQL expression for the filter.
*
* @throws NullPointerException if {@code sqlExpression} is null.
* @throws IllegalArgumentException if {@code sqlExpression} is an empty string.
*/
public SqlRuleFilter(String sqlExpression) {
final ClientLogger logger = new ClientLogger(SqlRuleFilter.class);
if (sqlExpression == null) {
throw logger.logExceptionAsError(new NullPointerException("'sqlExpression' cannot be null."));
} else if (sqlExpression.isEmpty()) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'sqlExpression' cannot be an empty string."));
}
this.sqlExpression = sqlExpression;
this.compatibilityLevel = null;
this.requiresPreprocessing = null;
}
/**
* Package private constructor for creating a model deserialised from the service.
*
* @param sqlExpression SQL expression for the filter.
* @param compatibilityLevel The compatibility level.
* @param requiresPreprocessing Whether or not it requires preprocessing
*/
SqlRuleFilter(String sqlExpression, String compatibilityLevel, Boolean requiresPreprocessing) {
this.sqlExpression = sqlExpression;
this.compatibilityLevel = compatibilityLevel;
this.requiresPreprocessing = requiresPreprocessing;
}
/**
* Gets the compatibility level.
*
* @return The compatibility level.
*/
String getCompatibilityLevel() {
return compatibilityLevel;
}
/**
* Gets whether or not requires preprocessing.
*
* @return Whether or not requires preprocessing.
*/
Boolean isPreprocessingRequired() {
return requiresPreprocessing;
}
/**
* Gets the value of a filter expression. Allowed types: string, int, long, bool, double
*
* @return Gets the value of a filter expression.
*/
public Map<String, Object> getParameters() {
return properties;
}
/**
* Gets the SQL expression.
*
* @return The SQL expression.
*/
public String getSqlExpression() {
return sqlExpression;
}
/**
* Converts the value of the current instance to its equivalent string representation.
*
* @return A string representation of the current instance.
*/
@Override
public String toString() {
return String.format("SqlRuleFilter: %s", sqlExpression);
}
/**
* Compares this RuleFilter to the specified object. The result is true if and only if the argument is not null
* and is a SqlRuleFilter object that with the same parameters as this object.
*
* @param other - the object to which the current SqlRuleFilter should be compared.
* @return True, if the passed object is a SqlRuleFilter with the same parameter values, False otherwise.
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof SqlRuleFilter)) {
return false;
}
SqlRuleFilter that = (SqlRuleFilter) other;
return sqlExpression.equals(that.sqlExpression)
&& Objects.equals(compatibilityLevel, that.compatibilityLevel)
&& Objects.equals(requiresPreprocessing, that.requiresPreprocessing)
&& Objects.equals(properties, that.properties);
}
/**
* Returns a hash code for this SqlRuleFilter, which is the hashcode for the SqlExpression.
*
* @return a hash code value for this object.
*/
@Override
} | class SqlRuleFilter extends RuleFilter {
private final Map<String, Object> properties = new HashMap<>();
private final String sqlExpression;
private final String compatibilityLevel;
private final Boolean requiresPreprocessing;
/**
* Creates a new instance with the given SQL expression.
*
* @param sqlExpression SQL expression for the filter.
*
* @throws NullPointerException if {@code sqlExpression} is null.
* @throws IllegalArgumentException if {@code sqlExpression} is an empty string.
*/
public SqlRuleFilter(String sqlExpression) {
final ClientLogger logger = new ClientLogger(SqlRuleFilter.class);
if (sqlExpression == null) {
throw logger.logExceptionAsError(new NullPointerException("'sqlExpression' cannot be null."));
} else if (sqlExpression.isEmpty()) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'sqlExpression' cannot be an empty string."));
}
this.sqlExpression = sqlExpression;
this.compatibilityLevel = null;
this.requiresPreprocessing = null;
}
/**
* Package private constructor for creating a model deserialised from the service.
*
* @param sqlExpression SQL expression for the filter.
* @param compatibilityLevel The compatibility level.
* @param requiresPreprocessing Whether or not it requires preprocessing
*/
SqlRuleFilter(String sqlExpression, String compatibilityLevel, Boolean requiresPreprocessing) {
this.sqlExpression = sqlExpression;
this.compatibilityLevel = compatibilityLevel;
this.requiresPreprocessing = requiresPreprocessing;
}
/**
* Gets the compatibility level.
*
* @return The compatibility level.
*/
String getCompatibilityLevel() {
return compatibilityLevel;
}
/**
* Gets whether or not requires preprocessing.
*
* @return Whether or not requires preprocessing.
*/
Boolean isPreprocessingRequired() {
return requiresPreprocessing;
}
/**
* Gets the value of a filter expression. Allowed types: string, int, long, bool, double
*
* @return Gets the value of a filter expression.
*/
public Map<String, Object> getParameters() {
return properties;
}
/**
* Gets the SQL expression.
*
* @return The SQL expression.
*/
public String getSqlExpression() {
return sqlExpression;
}
/**
* Converts the value of the current instance to its equivalent string representation.
*
* @return A string representation of the current instance.
*/
@Override
public String toString() {
return String.format("SqlRuleFilter: %s", sqlExpression);
}
/**
* Compares this RuleFilter to the specified object. The result is true if and only if the argument is not null
* and is a SqlRuleFilter object that with the same parameters as this object.
*
* @param other - the object to which the current SqlRuleFilter should be compared.
* @return True, if the passed object is a SqlRuleFilter with the same parameter values, False otherwise.
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof SqlRuleFilter)) {
return false;
}
SqlRuleFilter that = (SqlRuleFilter) other;
return sqlExpression.equals(that.sqlExpression)
&& Objects.equals(compatibilityLevel, that.compatibilityLevel)
&& Objects.equals(requiresPreprocessing, that.requiresPreprocessing)
&& Objects.equals(properties, that.properties);
}
/**
* Returns a hash code for this SqlRuleFilter, which is the hashcode for the SqlExpression.
*
* @return a hash code value for this object.
*/
@Override
} |
We could remove the outter "()", @chenrujun is this the way to fix the bug? Is the return value of `getPropertyNames()` correct now? | public boolean containsProperty(String name) {
return (getProperty(name) != null);
} | return (getProperty(name) != null); | public boolean containsProperty(String name) {
return getProperty(name) != null;
} | class KeyVaultPropertySource extends EnumerablePropertySource<KeyVaultOperation> {
private final KeyVaultOperation operations;
/**
* Create a new {@code KeyVaultPropertySource} with the given name and {@link KeyVaultOperation}.
* @param name the associated name
* @param operation the {@link KeyVaultOperation}
*/
public KeyVaultPropertySource(String name, KeyVaultOperation operation) {
super(name, operation);
this.operations = operation;
}
@Override
public String[] getPropertyNames() {
return this.operations.getPropertyNames();
}
@Override
public Object getProperty(String name) {
return operations.getProperty(name);
}
@Override
} | class KeyVaultPropertySource extends EnumerablePropertySource<KeyVaultOperation> {
private final KeyVaultOperation operations;
/**
* Create a new {@code KeyVaultPropertySource} with the given name and {@link KeyVaultOperation}.
* @param name the associated name
* @param operation the {@link KeyVaultOperation}
*/
public KeyVaultPropertySource(String name, KeyVaultOperation operation) {
super(name, operation);
this.operations = operation;
}
@Override
public String[] getPropertyNames() {
return this.operations.getPropertyNames();
}
@Override
public Object getProperty(String name) {
return operations.getProperty(name);
}
@Override
} |
> this the way to fix the bug? Yes. > Is the return value of getPropertyNames() correct now? No. It's still possible that a key can get value by `getProperty()`, but the key does not belong to the value returned by `getPropertyNames()`, it's a problem that first introduced here: https://github.com/microsoft/azure-spring-boot/pull/550/commits/cd12e47a465798d9b8ec2b6202dddd488205c508 | public boolean containsProperty(String name) {
return (getProperty(name) != null);
} | return (getProperty(name) != null); | public boolean containsProperty(String name) {
return getProperty(name) != null;
} | class KeyVaultPropertySource extends EnumerablePropertySource<KeyVaultOperation> {
private final KeyVaultOperation operations;
/**
* Create a new {@code KeyVaultPropertySource} with the given name and {@link KeyVaultOperation}.
* @param name the associated name
* @param operation the {@link KeyVaultOperation}
*/
public KeyVaultPropertySource(String name, KeyVaultOperation operation) {
super(name, operation);
this.operations = operation;
}
@Override
public String[] getPropertyNames() {
return this.operations.getPropertyNames();
}
@Override
public Object getProperty(String name) {
return operations.getProperty(name);
}
@Override
} | class KeyVaultPropertySource extends EnumerablePropertySource<KeyVaultOperation> {
private final KeyVaultOperation operations;
/**
* Create a new {@code KeyVaultPropertySource} with the given name and {@link KeyVaultOperation}.
* @param name the associated name
* @param operation the {@link KeyVaultOperation}
*/
public KeyVaultPropertySource(String name, KeyVaultOperation operation) {
super(name, operation);
this.operations = operation;
}
@Override
public String[] getPropertyNames() {
return this.operations.getPropertyNames();
}
@Override
public Object getProperty(String name) {
return operations.getProperty(name);
}
@Override
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.