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
talked offline. Will keep this method until code-gen fixes the issue. (We can't remove `AzureKeyCredentialTrait,`
public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); }
return this.credential((KeyCredential) azureKeyCredential);
public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override /** The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { KeyCredentialPolicy keyCredentialPolicy; if (endpoint != null) { keyCredentialPolicy = new KeyCredentialPolicy("api-key", keyCredential); } else { keyCredentialPolicy = new KeyCredentialPolicy("Authorization", keyCredential, "Bearer"); } policies.add(keyCredentialPolicy); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; } private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ public OpenAIAsyncClient buildAsyncClient() { if (this.endpoint != null) { return new OpenAIAsyncClient(buildInnerClient()); } return new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()); } /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ public OpenAIClient buildClient() { if (this.endpoint != null) { return new OpenAIClient(buildInnerClient()); } return new OpenAIClient(buildInnerNonAzureOpenAIClient()); } private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override /** The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { policies.add( useNonAzureOpenAIService() ? new KeyCredentialPolicy("Authorization", keyCredential, "Bearer") : new KeyCredentialPolicy("api-key", keyCredential)); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; } private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ public OpenAIAsyncClient buildAsyncClient() { return useNonAzureOpenAIService() ? new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()) : new OpenAIAsyncClient(buildInnerClient()); } /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ public OpenAIClient buildClient() { return useNonAzureOpenAIService() ? new OpenAIClient(buildInnerNonAzureOpenAIClient()) : new OpenAIClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); /** * OpenAI service can be used by either not setting the endpoint or by setting the endpoint to start with * "https: */ private boolean useNonAzureOpenAIService() { return endpoint == null || endpoint.startsWith(OPEN_AI_ENDPOINT); } }
If user doesn't provide endpoint, it should redirect to OpenAI and not Azure OpenAI.
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { KeyCredentialPolicy keyCredentialPolicy; if (endpoint != null && !endpoint.startsWith(OPEN_AI_ENDPOINT)) { keyCredentialPolicy = new KeyCredentialPolicy("api-key", keyCredential); } else { keyCredentialPolicy = new KeyCredentialPolicy("Authorization", keyCredential, "Bearer"); } policies.add(keyCredentialPolicy); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; }
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { policies.add( useNonAzureOpenAIService() ? new KeyCredentialPolicy("Authorization", keyCredential, "Bearer") : new KeyCredentialPolicy("api-key", keyCredential)); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); } /** The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ public OpenAIAsyncClient buildAsyncClient() { if (endpoint != null && !endpoint.startsWith(OPEN_AI_ENDPOINT)) { return new OpenAIAsyncClient(buildInnerClient()); } return new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()); } /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ public OpenAIClient buildClient() { if (endpoint != null && !endpoint.startsWith(OPEN_AI_ENDPOINT)) { return new OpenAIClient(buildInnerClient()); } return new OpenAIClient(buildInnerNonAzureOpenAIClient()); } private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); } /** The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ public OpenAIAsyncClient buildAsyncClient() { return useNonAzureOpenAIService() ? new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()) : new OpenAIAsyncClient(buildInnerClient()); } /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ public OpenAIClient buildClient() { return useNonAzureOpenAIService() ? new OpenAIClient(buildInnerNonAzureOpenAIClient()) : new OpenAIClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); /** * OpenAI service can be used by either not setting the endpoint or by setting the endpoint to start with * "https: */ private boolean useNonAzureOpenAIService() { return endpoint == null || endpoint.startsWith(OPEN_AI_ENDPOINT); } }
Update the comments here as well. OpenAI service can be used by either not setting the endpoint or by setting the endpoint to "https://api.openai.com/".
public OpenAIAsyncClient buildAsyncClient() { if (endpoint != null && !endpoint.startsWith(OPEN_AI_ENDPOINT)) { return new OpenAIAsyncClient(buildInnerClient()); } return new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()); }
public OpenAIAsyncClient buildAsyncClient() { return useNonAzureOpenAIService() ? new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()) : new OpenAIAsyncClient(buildInnerClient()); }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); } /** The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { KeyCredentialPolicy keyCredentialPolicy; if (endpoint != null && !endpoint.startsWith(OPEN_AI_ENDPOINT)) { keyCredentialPolicy = new KeyCredentialPolicy("api-key", keyCredential); } else { keyCredentialPolicy = new KeyCredentialPolicy("Authorization", keyCredential, "Bearer"); } policies.add(keyCredentialPolicy); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; } private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ public OpenAIClient buildClient() { if (endpoint != null && !endpoint.startsWith(OPEN_AI_ENDPOINT)) { return new OpenAIClient(buildInnerClient()); } return new OpenAIClient(buildInnerNonAzureOpenAIClient()); } private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); } /** The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { policies.add( useNonAzureOpenAIService() ? new KeyCredentialPolicy("Authorization", keyCredential, "Bearer") : new KeyCredentialPolicy("api-key", keyCredential)); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; } private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ public OpenAIClient buildClient() { return useNonAzureOpenAIService() ? new OpenAIClient(buildInnerNonAzureOpenAIClient()) : new OpenAIClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); /** * OpenAI service can be used by either not setting the endpoint or by setting the endpoint to start with * "https: */ private boolean useNonAzureOpenAIService() { return endpoint == null || endpoint.startsWith(OPEN_AI_ENDPOINT); } }
Instead of repeating this code, we should extract this to a method `useAzureOpenAI()`.
public OpenAIClient buildClient() { if (endpoint != null && !endpoint.startsWith(OPEN_AI_ENDPOINT)) { return new OpenAIClient(buildInnerClient()); } return new OpenAIClient(buildInnerNonAzureOpenAIClient()); }
return new OpenAIClient(buildInnerClient());
public OpenAIClient buildClient() { return useNonAzureOpenAIService() ? new OpenAIClient(buildInnerNonAzureOpenAIClient()) : new OpenAIClient(buildInnerClient()); }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); } /** The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { KeyCredentialPolicy keyCredentialPolicy; if (endpoint != null && !endpoint.startsWith(OPEN_AI_ENDPOINT)) { keyCredentialPolicy = new KeyCredentialPolicy("api-key", keyCredential); } else { keyCredentialPolicy = new KeyCredentialPolicy("Authorization", keyCredential, "Bearer"); } policies.add(keyCredentialPolicy); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; } private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ public OpenAIAsyncClient buildAsyncClient() { if (endpoint != null && !endpoint.startsWith(OPEN_AI_ENDPOINT)) { return new OpenAIAsyncClient(buildInnerClient()); } return new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()); } /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); }
class OpenAIClientBuilder implements HttpTrait<OpenAIClientBuilder>, ConfigurationTrait<OpenAIClientBuilder>, TokenCredentialTrait<OpenAIClientBuilder>, AzureKeyCredentialTrait<OpenAIClientBuilder>, EndpointTrait<OpenAIClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; @Generated private static final String[] DEFAULT_SCOPES = new String[] {"https: @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-openai.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** Create an instance of the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The TokenCredential used for authentication. */ @Generated private TokenCredential tokenCredential; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /* * The AzureKeyCredential used for authentication. */ @Generated private AzureKeyCredential azureKeyCredential; /** {@inheritDoc}. */ @Override public OpenAIClientBuilder credential(AzureKeyCredential azureKeyCredential) { return this.credential((KeyCredential) azureKeyCredential); } /** The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. */ private KeyCredential keyCredential; /** * The KeyCredential used for OpenAi authentication. It could be either of Azure or Non-Azure OpenAI API key. * * @param keyCredential The credential for OpenAI authentication. * @return the object itself. */ public OpenAIClientBuilder credential(KeyCredential keyCredential) { this.keyCredential = keyCredential; return this; } /* * The service endpoint */ @Generated private String endpoint; /** {@inheritDoc}. */ @Generated @Override public OpenAIClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * Service version */ @Generated private OpenAIServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder serviceVersion(OpenAIServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the OpenAIClientBuilder. */ @Generated public OpenAIClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Builds an instance of OpenAIClientImpl with the provided parameters. * * @return an instance of OpenAIClientImpl. */ @Generated private OpenAIClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); OpenAIServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : OpenAIServiceVersion.getLatest(); OpenAIClientImpl client = new OpenAIClientImpl( localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); return client; } private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); policies.add(new CookiePolicy()); if (keyCredential != null) { policies.add( useNonAzureOpenAIService() ? new KeyCredentialPolicy("Authorization", keyCredential, "Bearer") : new KeyCredentialPolicy("api-key", keyCredential)); } if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .build(); return httpPipeline; } private NonAzureOpenAIClientImpl buildInnerNonAzureOpenAIClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); NonAzureOpenAIClientImpl client = new NonAzureOpenAIClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter()); return client; } /** * Builds an instance of OpenAIAsyncClient class. * * @return an instance of OpenAIAsyncClient. */ public OpenAIAsyncClient buildAsyncClient() { return useNonAzureOpenAIService() ? new OpenAIAsyncClient(buildInnerNonAzureOpenAIClient()) : new OpenAIAsyncClient(buildInnerClient()); } /** * Builds an instance of OpenAIClient class. * * @return an instance of OpenAIClient. */ private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientBuilder.class); /** * OpenAI service can be used by either not setting the endpoint or by setting the endpoint to start with * "https: */ private boolean useNonAzureOpenAIService() { return endpoint == null || endpoint.startsWith(OPEN_AI_ENDPOINT); } }
Should we log the error?
public String toString() { try { return Utils.getSimpleObjectMapper().writeValueAsString(this); } catch (final JsonProcessingException error) { return "null"; } }
return "null";
public String toString() { try { return Utils.getDurationEnabledObjectMapper().writeValueAsString(this); } catch (final JsonProcessingException error) { LOGGER.debug("could not convert {} value to JSON due to:", this.getClass(), error); try { return lenientFormat("{\"error\":%s}", Utils.getDurationEnabledObjectMapper().writeValueAsString(error.toString())); } catch (final JsonProcessingException exception) { return "null"; } } }
class QueryMetrics { private final long retrievedDocumentCount; private final long retrievedDocumentSize; private final long outputDocumentCount; private final long outputDocumentSize; private final long indexHitDocumentCount; private final Duration totalQueryExecutionTime; private final QueryPreparationTimes queryPreparationTimes; private final Duration indexLookupTime; private final Duration documentLoadTime; private final Duration vmExecutionTime; private final RuntimeExecutionTimes runtimeExecutionTimes; private final Duration documentWriteTime; private final ClientSideMetrics clientSideMetrics; private final List<String> activityIds; private final IndexUtilizationInfo indexUtilizationInfo; public QueryMetrics(List<String> activities, long retrievedDocumentCount, long retrievedDocumentSize, long outputDocumentCount, long outputDocumentSize, long indexHitCount, Duration totalQueryExecutionTime, QueryPreparationTimes queryPreparationTimes, Duration indexLookupTime, Duration documentLoadTime, Duration vmExecutionTime, RuntimeExecutionTimes runtimeExecutionTimes, Duration documentWriteTime, ClientSideMetrics clientSideMetrics, IndexUtilizationInfo indexUtilizationInfo) { this.retrievedDocumentCount = retrievedDocumentCount; this.retrievedDocumentSize = retrievedDocumentSize; this.outputDocumentCount = outputDocumentCount; this.outputDocumentSize = outputDocumentSize; this.indexHitDocumentCount = indexHitCount; this.totalQueryExecutionTime = totalQueryExecutionTime; this.queryPreparationTimes = queryPreparationTimes; this.indexLookupTime = indexLookupTime; this.documentLoadTime = documentLoadTime; this.vmExecutionTime = vmExecutionTime; this.runtimeExecutionTimes = runtimeExecutionTimes; this.documentWriteTime = documentWriteTime; this.clientSideMetrics = clientSideMetrics; this.activityIds = activities; this.indexUtilizationInfo = indexUtilizationInfo; } /** * @return the retrievedDocumentCount */ public long getRetrievedDocumentCount() { return retrievedDocumentCount; } /** * @return the retrievedDocumentSize */ public long getRetrievedDocumentSize() { return retrievedDocumentSize; } /** * @return the outputDocumentCount */ public long getOutputDocumentCount() { return outputDocumentCount; } /** * @return the outputDocumentSize */ public long getOutputDocumentSize() { return outputDocumentSize; } /** * @return the indexHitDocumentCount */ public long getIndexHitDocumentCount() { return indexHitDocumentCount; } /** * Gets the index hit ratio by query in the Azure Cosmos database service. * * @return the IndexHitRatio */ public double getIndexHitRatio() { return this.retrievedDocumentCount == 0 ? 1 : (double) this.indexHitDocumentCount / this.retrievedDocumentCount; } /** * @return the totalQueryExecutionTime */ public Duration getTotalQueryExecutionTime() { return totalQueryExecutionTime; } /** * @return the queryPreparationTimes */ public QueryPreparationTimes getQueryPreparationTimes() { return queryPreparationTimes; } /** * @return the indexLookupTime */ public Duration getIndexLookupTime() { return indexLookupTime; } /** * @return the documentLoadTime */ public Duration getDocumentLoadTime() { return documentLoadTime; } /** * @return the vmExecutionTime */ public Duration getVMExecutionTime() { return vmExecutionTime; } /** * @return the runtimeExecutionTimes */ public RuntimeExecutionTimes getRuntimeExecutionTimes() { return runtimeExecutionTimes; } /** * @return the documentWriteTime */ public Duration getDocumentWriteTime() { return documentWriteTime; } /** * @return the clientSideMetrics */ public ClientSideMetrics getClientSideMetrics() { return clientSideMetrics; } /** * @return the indexUtilizationInfo */ public IndexUtilizationInfo getIndexUtilizationInfo() { return indexUtilizationInfo; } /** * @return number of reties in the Azure Cosmos database service. */ public long getRetries() { return this.clientSideMetrics.getRetries(); } public static QueryMetrics addQueryMetrics(QueryMetrics... additionalQueryMetrics) { List<QueryMetrics> queryMetricsList = new ArrayList<>(Arrays.asList(additionalQueryMetrics)); return QueryMetrics.createFromCollection(queryMetricsList); } /** * Utility method to merge two query metrics map. * @param base metrics map which will be updated with new values. * @param addOn metrics map whose values will be merge in base map. */ public static void mergeQueryMetricsMap(Map<String, QueryMetrics> base, Map<String, QueryMetrics> addOn) { for (Map.Entry<String, QueryMetrics> entry : addOn.entrySet()) { base.compute(entry.getKey(), (key, value) -> { if (value == null) { return entry.getValue(); } else { return QueryMetrics.addQueryMetrics(value, entry.getValue()); } }); } } public static QueryMetrics createFromCollection(Collection<QueryMetrics> queryMetricsCollection) { long retrievedDocumentCount = 0; long retrievedDocumentSize = 0; long outputDocumentCount = 0; long outputDocumentSize = 0; long indexHitDocumentCount = 0; Duration totalQueryExecutionTime = Duration.ZERO; Collection<QueryPreparationTimes> queryPreparationTimesCollection = new ArrayList<QueryPreparationTimes>(); Duration indexLookupTime = Duration.ZERO; Duration documentLoadTime = Duration.ZERO; Duration vmExecutionTime = Duration.ZERO; Collection<RuntimeExecutionTimes> runtimeExecutionTimesCollection = new ArrayList<RuntimeExecutionTimes>(); Duration documentWriteTime = Duration.ZERO; Collection<ClientSideMetrics> clientSideMetricsCollection = new ArrayList<ClientSideMetrics>(); List<String> activityIds = new ArrayList<>(); Collection<IndexUtilizationInfo> indexUtilizationInfoCollection = new ArrayList<IndexUtilizationInfo>(); for (QueryMetrics queryMetrics : queryMetricsCollection) { if (queryMetrics == null) { throw new NullPointerException("queryMetricsList can not have null elements"); } activityIds.addAll(queryMetrics.activityIds); retrievedDocumentCount += queryMetrics.retrievedDocumentCount; retrievedDocumentSize += queryMetrics.retrievedDocumentSize; outputDocumentCount += queryMetrics.outputDocumentCount; outputDocumentSize += queryMetrics.outputDocumentSize; indexHitDocumentCount += queryMetrics.indexHitDocumentCount; totalQueryExecutionTime = totalQueryExecutionTime.plus(queryMetrics.totalQueryExecutionTime); queryPreparationTimesCollection.add(queryMetrics.queryPreparationTimes); indexLookupTime = indexLookupTime.plus(queryMetrics.indexLookupTime); documentLoadTime = documentLoadTime.plus(queryMetrics.documentLoadTime); vmExecutionTime = vmExecutionTime.plus(queryMetrics.vmExecutionTime); runtimeExecutionTimesCollection.add(queryMetrics.runtimeExecutionTimes); documentWriteTime = documentWriteTime.plus(queryMetrics.documentWriteTime); clientSideMetricsCollection.add(queryMetrics.clientSideMetrics); indexUtilizationInfoCollection.add(queryMetrics.indexUtilizationInfo); } return new QueryMetrics(activityIds, retrievedDocumentCount, retrievedDocumentSize, outputDocumentCount, outputDocumentSize, indexHitDocumentCount, totalQueryExecutionTime, QueryPreparationTimes.createFromCollection(queryPreparationTimesCollection), indexLookupTime, documentLoadTime, vmExecutionTime, RuntimeExecutionTimes.createFromCollection(runtimeExecutionTimesCollection), documentWriteTime, ClientSideMetrics.createFromCollection(clientSideMetricsCollection), IndexUtilizationInfo.createFromCollection(indexUtilizationInfoCollection)); } public static QueryMetrics createFromDelimitedString(String delimitedString) { return QueryMetrics.createFromDelimitedStringAndClientSideMetrics(delimitedString, new ClientSideMetrics(0, 0, new ArrayList<FetchExecutionRange>(), new ArrayList<ImmutablePair<String, SchedulingTimeSpan>>()), "", ""); } public static QueryMetrics createFromDelimitedStringAndClientSideMetrics(String delimitedString, ClientSideMetrics clientSideMetrics, String activityId, String indexUtilizationInfoJSONString) { HashMap<String, Double> metrics = QueryMetricsUtils.parseDelimitedString(delimitedString); double indexHitRatio; double retrievedDocumentCount; indexHitRatio = metrics.get(QueryMetricsConstants.IndexHitRatio); retrievedDocumentCount = metrics.get(QueryMetricsConstants.RetrievedDocumentCount); long indexHitCount = (long) (indexHitRatio * retrievedDocumentCount); double outputDocumentCount = metrics.get(QueryMetricsConstants.OutputDocumentCount); double outputDocumentSize = metrics.get(QueryMetricsConstants.OutputDocumentSize); double retrievedDocumentSize = metrics.get(QueryMetricsConstants.RetrievedDocumentSize); Duration totalQueryExecutionTime = QueryMetricsUtils.getDurationFromMetrics(metrics, QueryMetricsConstants.TotalQueryExecutionTimeInMs); IndexUtilizationInfo indexUtilizationInfo = null; if (indexUtilizationInfoJSONString != null) { indexUtilizationInfo = IndexUtilizationInfo.createFromJSONString(Utils.decodeBase64String(indexUtilizationInfoJSONString)); } List<String> activities = new ArrayList<>(); activities.add(activityId); return new QueryMetrics( activities, (long) retrievedDocumentCount, (long) retrievedDocumentSize, (long) outputDocumentCount, (long) outputDocumentSize, indexHitCount, totalQueryExecutionTime, QueryPreparationTimes.createFromDelimitedString(delimitedString), QueryMetricsUtils.getDurationFromMetrics(metrics, QueryMetricsConstants.IndexLookupTimeInMs), QueryMetricsUtils.getDurationFromMetrics(metrics, QueryMetricsConstants.DocumentLoadTimeInMs), QueryMetricsUtils.getDurationFromMetrics(metrics, QueryMetricsConstants.VMExecutionTimeInMs), RuntimeExecutionTimes.createFromDelimitedString(delimitedString), QueryMetricsUtils.getDurationFromMetrics(metrics, QueryMetricsConstants.DocumentWriteTimeInMs), clientSideMetrics, indexUtilizationInfo); } @Override }
class QueryMetrics { private static final Logger LOGGER = LoggerFactory.getLogger(QueryMetrics.class); private final long retrievedDocumentCount; private final long retrievedDocumentSize; private final long outputDocumentCount; private final long outputDocumentSize; private final long indexHitDocumentCount; private final Duration totalQueryExecutionTime; private final QueryPreparationTimes queryPreparationTimes; private final Duration indexLookupTime; private final Duration documentLoadTime; private final Duration vmExecutionTime; private final RuntimeExecutionTimes runtimeExecutionTimes; private final Duration documentWriteTime; private final ClientSideMetrics clientSideMetrics; private final List<String> activityIds; private final IndexUtilizationInfo indexUtilizationInfo; public QueryMetrics(List<String> activities, long retrievedDocumentCount, long retrievedDocumentSize, long outputDocumentCount, long outputDocumentSize, long indexHitCount, Duration totalQueryExecutionTime, QueryPreparationTimes queryPreparationTimes, Duration indexLookupTime, Duration documentLoadTime, Duration vmExecutionTime, RuntimeExecutionTimes runtimeExecutionTimes, Duration documentWriteTime, ClientSideMetrics clientSideMetrics, IndexUtilizationInfo indexUtilizationInfo) { this.retrievedDocumentCount = retrievedDocumentCount; this.retrievedDocumentSize = retrievedDocumentSize; this.outputDocumentCount = outputDocumentCount; this.outputDocumentSize = outputDocumentSize; this.indexHitDocumentCount = indexHitCount; this.totalQueryExecutionTime = totalQueryExecutionTime; this.queryPreparationTimes = queryPreparationTimes; this.indexLookupTime = indexLookupTime; this.documentLoadTime = documentLoadTime; this.vmExecutionTime = vmExecutionTime; this.runtimeExecutionTimes = runtimeExecutionTimes; this.documentWriteTime = documentWriteTime; this.clientSideMetrics = clientSideMetrics; this.activityIds = activities; this.indexUtilizationInfo = indexUtilizationInfo; } /** * @return the retrievedDocumentCount */ public long getRetrievedDocumentCount() { return retrievedDocumentCount; } /** * @return the retrievedDocumentSize */ public long getRetrievedDocumentSize() { return retrievedDocumentSize; } /** * @return the outputDocumentCount */ public long getOutputDocumentCount() { return outputDocumentCount; } /** * @return the outputDocumentSize */ public long getOutputDocumentSize() { return outputDocumentSize; } /** * @return the indexHitDocumentCount */ public long getIndexHitDocumentCount() { return indexHitDocumentCount; } /** * Gets the index hit ratio by query in the Azure Cosmos database service. * * @return the IndexHitRatio */ public double getIndexHitRatio() { return this.retrievedDocumentCount == 0 ? 1 : (double) this.indexHitDocumentCount / this.retrievedDocumentCount; } /** * @return the totalQueryExecutionTime */ public Duration getTotalQueryExecutionTime() { return totalQueryExecutionTime; } /** * @return the queryPreparationTimes */ public QueryPreparationTimes getQueryPreparationTimes() { return queryPreparationTimes; } /** * @return the indexLookupTime */ public Duration getIndexLookupTime() { return indexLookupTime; } /** * @return the documentLoadTime */ public Duration getDocumentLoadTime() { return documentLoadTime; } /** * @return the vmExecutionTime */ public Duration getVMExecutionTime() { return vmExecutionTime; } /** * @return the runtimeExecutionTimes */ public RuntimeExecutionTimes getRuntimeExecutionTimes() { return runtimeExecutionTimes; } /** * @return the documentWriteTime */ public Duration getDocumentWriteTime() { return documentWriteTime; } /** * @return the clientSideMetrics */ public ClientSideMetrics getClientSideMetrics() { return clientSideMetrics; } /** * @return the indexUtilizationInfo */ public IndexUtilizationInfo getIndexUtilizationInfo() { return indexUtilizationInfo; } /** * @return number of reties in the Azure Cosmos database service. */ public long getRetries() { return this.clientSideMetrics.getRetries(); } public static QueryMetrics addQueryMetrics(QueryMetrics... additionalQueryMetrics) { List<QueryMetrics> queryMetricsList = new ArrayList<>(Arrays.asList(additionalQueryMetrics)); return QueryMetrics.createFromCollection(queryMetricsList); } /** * Utility method to merge two query metrics map. * @param base metrics map which will be updated with new values. * @param addOn metrics map whose values will be merge in base map. */ public static void mergeQueryMetricsMap(Map<String, QueryMetrics> base, Map<String, QueryMetrics> addOn) { for (Map.Entry<String, QueryMetrics> entry : addOn.entrySet()) { base.compute(entry.getKey(), (key, value) -> { if (value == null) { return entry.getValue(); } else { return QueryMetrics.addQueryMetrics(value, entry.getValue()); } }); } } public static QueryMetrics createFromCollection(Collection<QueryMetrics> queryMetricsCollection) { long retrievedDocumentCount = 0; long retrievedDocumentSize = 0; long outputDocumentCount = 0; long outputDocumentSize = 0; long indexHitDocumentCount = 0; Duration totalQueryExecutionTime = Duration.ZERO; Collection<QueryPreparationTimes> queryPreparationTimesCollection = new ArrayList<QueryPreparationTimes>(); Duration indexLookupTime = Duration.ZERO; Duration documentLoadTime = Duration.ZERO; Duration vmExecutionTime = Duration.ZERO; Collection<RuntimeExecutionTimes> runtimeExecutionTimesCollection = new ArrayList<RuntimeExecutionTimes>(); Duration documentWriteTime = Duration.ZERO; Collection<ClientSideMetrics> clientSideMetricsCollection = new ArrayList<ClientSideMetrics>(); List<String> activityIds = new ArrayList<>(); Collection<IndexUtilizationInfo> indexUtilizationInfoCollection = new ArrayList<IndexUtilizationInfo>(); for (QueryMetrics queryMetrics : queryMetricsCollection) { if (queryMetrics == null) { throw new NullPointerException("queryMetricsList can not have null elements"); } activityIds.addAll(queryMetrics.activityIds); retrievedDocumentCount += queryMetrics.retrievedDocumentCount; retrievedDocumentSize += queryMetrics.retrievedDocumentSize; outputDocumentCount += queryMetrics.outputDocumentCount; outputDocumentSize += queryMetrics.outputDocumentSize; indexHitDocumentCount += queryMetrics.indexHitDocumentCount; totalQueryExecutionTime = totalQueryExecutionTime.plus(queryMetrics.totalQueryExecutionTime); queryPreparationTimesCollection.add(queryMetrics.queryPreparationTimes); indexLookupTime = indexLookupTime.plus(queryMetrics.indexLookupTime); documentLoadTime = documentLoadTime.plus(queryMetrics.documentLoadTime); vmExecutionTime = vmExecutionTime.plus(queryMetrics.vmExecutionTime); runtimeExecutionTimesCollection.add(queryMetrics.runtimeExecutionTimes); documentWriteTime = documentWriteTime.plus(queryMetrics.documentWriteTime); clientSideMetricsCollection.add(queryMetrics.clientSideMetrics); indexUtilizationInfoCollection.add(queryMetrics.indexUtilizationInfo); } return new QueryMetrics(activityIds, retrievedDocumentCount, retrievedDocumentSize, outputDocumentCount, outputDocumentSize, indexHitDocumentCount, totalQueryExecutionTime, QueryPreparationTimes.createFromCollection(queryPreparationTimesCollection), indexLookupTime, documentLoadTime, vmExecutionTime, RuntimeExecutionTimes.createFromCollection(runtimeExecutionTimesCollection), documentWriteTime, ClientSideMetrics.createFromCollection(clientSideMetricsCollection), IndexUtilizationInfo.createFromCollection(indexUtilizationInfoCollection)); } public static QueryMetrics createFromDelimitedString(String delimitedString) { return QueryMetrics.createFromDelimitedStringAndClientSideMetrics(delimitedString, new ClientSideMetrics(0, 0, new ArrayList<FetchExecutionRange>(), new ArrayList<ImmutablePair<String, SchedulingTimeSpan>>()), "", ""); } public static QueryMetrics createFromDelimitedStringAndClientSideMetrics(String delimitedString, ClientSideMetrics clientSideMetrics, String activityId, String indexUtilizationInfoJSONString) { HashMap<String, Double> metrics = QueryMetricsUtils.parseDelimitedString(delimitedString); double indexHitRatio; double retrievedDocumentCount; indexHitRatio = metrics.get(QueryMetricsConstants.IndexHitRatio); retrievedDocumentCount = metrics.get(QueryMetricsConstants.RetrievedDocumentCount); long indexHitCount = (long) (indexHitRatio * retrievedDocumentCount); double outputDocumentCount = metrics.get(QueryMetricsConstants.OutputDocumentCount); double outputDocumentSize = metrics.get(QueryMetricsConstants.OutputDocumentSize); double retrievedDocumentSize = metrics.get(QueryMetricsConstants.RetrievedDocumentSize); Duration totalQueryExecutionTime = QueryMetricsUtils.getDurationFromMetrics(metrics, QueryMetricsConstants.TotalQueryExecutionTimeInMs); IndexUtilizationInfo indexUtilizationInfo = null; if (indexUtilizationInfoJSONString != null) { indexUtilizationInfo = IndexUtilizationInfo.createFromJSONString(Utils.decodeBase64String(indexUtilizationInfoJSONString)); } List<String> activities = new ArrayList<>(); activities.add(activityId); return new QueryMetrics( activities, (long) retrievedDocumentCount, (long) retrievedDocumentSize, (long) outputDocumentCount, (long) outputDocumentSize, indexHitCount, totalQueryExecutionTime, QueryPreparationTimes.createFromDelimitedString(delimitedString), QueryMetricsUtils.getDurationFromMetrics(metrics, QueryMetricsConstants.IndexLookupTimeInMs), QueryMetricsUtils.getDurationFromMetrics(metrics, QueryMetricsConstants.DocumentLoadTimeInMs), QueryMetricsUtils.getDurationFromMetrics(metrics, QueryMetricsConstants.VMExecutionTimeInMs), RuntimeExecutionTimes.createFromDelimitedString(delimitedString), QueryMetricsUtils.getDurationFromMetrics(metrics, QueryMetricsConstants.DocumentWriteTimeInMs), clientSideMetrics, indexUtilizationInfo); } @Override }
why do we need the filter provider?
private static ObjectMapper createAndInitializeDurationObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); SimpleFilterProvider filterProvider = new SimpleFilterProvider(); objectMapper.registerModule(new SimpleModule() .addSerializer(Duration.class, ToStringSerializer.instance) .addDeserializer(Duration.class, DurationDeserializer.INSTANCE) .addSerializer(Instant.class, ToStringSerializer.instance)) .setFilterProvider(filterProvider); return objectMapper; }
.setFilterProvider(filterProvider);
private static ObjectMapper createAndInitializeDurationObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new SimpleModule() .addSerializer(Duration.class, ToStringSerializer.instance) .addSerializer(Instant.class, ToStringSerializer.instance)); return objectMapper; }
class Utils { private final static Logger logger = LoggerFactory.getLogger(Utils.class); private static final int JAVA_VERSION = getJavaVersion(); private static final int ONE_KB = 1024; private static final ZoneId GMT_ZONE_ID = ZoneId.of("GMT"); public static final Base64.Encoder Base64Encoder = Base64.getEncoder(); public static final Base64.Decoder Base64Decoder = Base64.getDecoder(); public static final Base64.Encoder Base64UrlEncoder = Base64.getUrlEncoder(); private static final ObjectMapper simpleObjectMapperAllowingDuplicatedProperties = createAndInitializeObjectMapper(true); private static final ObjectMapper simpleObjectMapperDisallowingDuplicatedProperties = createAndInitializeObjectMapper(false); private static final ObjectMapper durationEnabledObjectMapper = createAndInitializeDurationObjectMapper(); private static ObjectMapper simpleObjectMapper = simpleObjectMapperDisallowingDuplicatedProperties; private static final TimeBasedGenerator TIME_BASED_GENERATOR = Generators.timeBasedGenerator(EthernetAddress.constructMulticastAddress()); private static final Pattern SPACE_PATTERN = Pattern.compile("\\s"); private static final DateTimeFormatter RFC_1123_DATE_TIME = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); private static ObjectMapper createAndInitializeObjectMapper(boolean allowDuplicateProperties) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); if (!allowDuplicateProperties) { objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); } objectMapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false); if (JAVA_VERSION != -1 && JAVA_VERSION < 16) { objectMapper.registerModule(new AfterburnerModule()); } objectMapper.registerModule(new JavaTimeModule()); return objectMapper; } private static int getJavaVersion() { int version = -1; try { String completeJavaVersion = System.getProperty("java.version"); String[] versionElements = completeJavaVersion.split("\\."); int versionFirstPart = Integer.parseInt(versionElements[0]); if (versionFirstPart == 1) { version = Integer.parseInt(versionElements[1]); } else { version = versionFirstPart; } return version; } catch (Exception ex) { logger.warn("Error while fetching java version", ex); return version; } } public static byte[] getUTF8BytesOrNull(String str) { if (str == null) { return null; } return str.getBytes(StandardCharsets.UTF_8); } public static byte[] getUTF8Bytes(String str) { return str.getBytes(StandardCharsets.UTF_8); } public static String encodeBase64String(byte[] binaryData) { String encodedString = Base64Encoder.encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static String decodeBase64String(String encodedString) { byte[] decodeString = Base64Decoder.decode(encodedString); return new String(decodeString, StandardCharsets.UTF_8); } public static String decodeAsUTF8String(String inputString) { if (inputString == null || inputString.isEmpty()) { return inputString; } try { return URLDecoder.decode(inputString, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { logger.warn("Error while decoding input string", e); return inputString; } } public static String encodeUrlBase64String(byte[] binaryData) { String encodedString = Base64UrlEncoder.withoutPadding().encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static void configureSimpleObjectMapper(boolean allowDuplicateProperties) { if (allowDuplicateProperties) { Utils.simpleObjectMapper = Utils.simpleObjectMapperAllowingDuplicatedProperties; } else { Utils.simpleObjectMapper = Utils.simpleObjectMapperDisallowingDuplicatedProperties; } } /** * Joins the specified paths by appropriately padding them with '/' * * @param path1 the first path segment to join. * @param path2 the second path segment to join. * @return the concatenated path with '/' */ public static String joinPath(String path1, String path2) { path1 = trimBeginningAndEndingSlashes(path1); String result = "/" + path1 + "/"; if (!StringUtils.isEmpty(path2)) { path2 = trimBeginningAndEndingSlashes(path2); result += path2 + "/"; } return result; } /** * Trims the beginning and ending '/' from the given path * * @param path the path to trim for beginning and ending slashes * @return the path without beginning and ending '/' */ public static String trimBeginningAndEndingSlashes(String path) { if(path == null) { return null; } if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path; } public static String createQuery(Map<String, String> queryParameters) { if (queryParameters == null) return ""; StringBuilder queryString = new StringBuilder(); for (Map.Entry<String, String> nameValuePair : queryParameters.entrySet()) { String key = nameValuePair.getKey(); String value = nameValuePair.getValue(); if (key != null && !key.isEmpty()) { if (queryString.length() > 0) { queryString.append(RuntimeConstants.Separators.Query[1]); } queryString.append(key); if (value != null) { queryString.append(RuntimeConstants.Separators.Query[2]); queryString.append(value); } } } return queryString.toString(); } public static URI setQuery(String urlString, String query) { if (urlString == null) throw new IllegalStateException("urlString parameter can't be null."); query = Utils.removeLeadingQuestionMark(query); try { if (query != null && !query.isEmpty()) { return new URI(Utils.addTrailingSlash(urlString) + RuntimeConstants.Separators.Query[0] + query); } else { return new URI(Utils.addTrailingSlash(urlString)); } } catch (URISyntaxException e) { throw new IllegalStateException("Uri is invalid: ", e); } } /** * Given the full path to a resource, extract the collection path. * * @param resourceFullName the full path to the resource. * @return the path of the collection in which the resource is. */ public static String getCollectionName(String resourceFullName) { if (resourceFullName != null) { resourceFullName = Utils.trimBeginningAndEndingSlashes(resourceFullName); int slashCount = 0; for (int i = 0; i < resourceFullName.length(); i++) { if (resourceFullName.charAt(i) == '/') { slashCount++; if (slashCount == 4) { return resourceFullName.substring(0, i); } } } } return resourceFullName; } public static <T> int getCollectionSize(Collection<T> collection) { if (collection == null) { return 0; } return collection.size(); } public static boolean isCollectionChild(ResourceType type) { return type == ResourceType.Document || type == ResourceType.Attachment || type == ResourceType.Conflict || type == ResourceType.StoredProcedure || type == ResourceType.Trigger || type == ResourceType.UserDefinedFunction; } public static boolean isWriteOperation(OperationType operationType) { return operationType == OperationType.Create || operationType == OperationType.Upsert || operationType == OperationType.Delete || operationType == OperationType.Replace || operationType == OperationType.ExecuteJavaScript || operationType == OperationType.Batch; } private static String addTrailingSlash(String path) { if (path == null || path.isEmpty()) path = new String(RuntimeConstants.Separators.Url); else if (path.charAt(path.length() - 1) != RuntimeConstants.Separators.Url[0]) path = path + RuntimeConstants.Separators.Url[0]; return path; } private static String removeLeadingQuestionMark(String path) { if (path == null || path.isEmpty()) return path; if (path.charAt(0) == RuntimeConstants.Separators.Query[0]) return path.substring(1); return path; } public static boolean isValidConsistency(ConsistencyLevel backendConsistency, ConsistencyLevel desiredConsistency) { switch (backendConsistency) { case STRONG: return desiredConsistency == ConsistencyLevel.STRONG || desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case BOUNDED_STALENESS: return desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case SESSION: case EVENTUAL: case CONSISTENT_PREFIX: return desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; default: throw new IllegalArgumentException("backendConsistency"); } } public static String getUserAgent() { return getUserAgent(HttpConstants.Versions.SDK_NAME, HttpConstants.Versions.getSdkVersion()); } public static String getUserAgent(String sdkName, String sdkVersion) { String osName = System.getProperty("os.name"); if (osName == null) { osName = "Unknown"; } osName = SPACE_PATTERN.matcher(osName).replaceAll(""); return String.format("%s%s/%s %s/%s JRE/%s", UserAgentContainer.AZSDK_USERAGENT_PREFIX, sdkName, sdkVersion, osName, System.getProperty("os.version"), System.getProperty("java.version") ); } public static ObjectMapper getSimpleObjectMapper() { return Utils.simpleObjectMapper; } public static ObjectMapper getDurationEnabledObjectMapper() { return Utils.durationEnabledObjectMapper; } /** * Returns Current Time in RFC 1123 format, e.g, * Fri, 01 Dec 2017 19:22:30 GMT. * * @return an instance of STRING */ public static String nowAsRFC1123() { ZonedDateTime now = ZonedDateTime.now(GMT_ZONE_ID); return Utils.RFC_1123_DATE_TIME.format(now); } public static UUID randomUUID() { return TIME_BASED_GENERATOR.generate(); } public static String instantAsUTCRFC1123(Instant instant){ return Utils.RFC_1123_DATE_TIME.format(instant.atZone(GMT_ZONE_ID)); } public static int getValueOrDefault(Integer val, int defaultValue) { return val != null ? val : defaultValue; } public static void checkStateOrThrow(boolean value, String argumentName, String message) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, message); if (t != null) { throw t; } } public static void checkNotNullOrThrow(Object val, String argumentName, String message) throws NullPointerException { NullPointerException t = checkNotNullOrReturnException(val, argumentName, message); if (t != null) { throw t; } } public static void checkStateOrThrow(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, argumentName, messageTemplateParams); if (t != null) { throw t; } } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String message) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, message)); } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } private static NullPointerException checkNotNullOrReturnException(Object val, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (val != null) { return null; } return new NullPointerException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } @SuppressWarnings("unchecked") public static <O, I> O as(I i, Class<O> klass) { if (i == null) { return null; } if (klass.isInstance(i)) { return (O) i; } else { return null; } } @SuppressWarnings("unchecked") public static <V> List<V> immutableListOf() { return Collections.EMPTY_LIST; } public static <K, V> Map<K, V>immutableMapOf(K k1, V v1) { Map<K, V> map = new HashMap<>(); map.put(k1, v1); map = Collections.unmodifiableMap(map); return map; } public static <V> V firstOrDefault(List<V> list) { return list.size() > 0? list.get(0) : null ; } public static class ValueHolder<V> { public ValueHolder() { } public ValueHolder(V v) { this.v = v; } public V v; public static <T> ValueHolder<T> initialize(T v) { return new ValueHolder<>(v); } } public static <K, V> boolean tryGetValue(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.get(key); return holder.v != null; } public static <K, V> boolean tryRemove(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.remove(key); return holder.v != null; } public static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) { if (StringUtils.isEmpty(itemResponseBodyAsString)) { return null; } try { return getSimpleObjectMapper().readValue(itemResponseBodyAsString, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse string [%s] to POJO.", itemResponseBodyAsString), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType) { if (Utils.isEmpty(item)) { return null; } try { return getSimpleObjectMapper().readValue(item, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse byte-array %s to POJO.", Arrays.toString(item)), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType, ItemDeserializer itemDeserializer) { if (Utils.isEmpty(item)) { return null; } if (itemDeserializer == null) { return Utils.parse(item, itemClassType); } return itemDeserializer.parseFrom(itemClassType, item); } public static ByteBuffer serializeJsonToByteBuffer(ObjectMapper objectMapper, Object object) { try { ByteBufferOutputStream byteBufferOutputStream = new ByteBufferOutputStream(ONE_KB); objectMapper.writeValue(byteBufferOutputStream, object); return byteBufferOutputStream.asByteBuffer(); } catch (IOException e) { throw new IllegalArgumentException("Failed to serialize the object into json", e); } } public static boolean isEmpty(byte[] bytes) { return bytes == null || bytes.length == 0; } public static String utf8StringFromOrNull(byte[] bytes) { if (bytes == null) { return null; } return new String(bytes, StandardCharsets.UTF_8); } public static void setContinuationTokenAndMaxItemCount(CosmosPagedFluxOptions pagedFluxOptions, CosmosQueryRequestOptions cosmosQueryRequestOptions) { if (pagedFluxOptions == null) { return; } if (pagedFluxOptions.getRequestContinuation() != null) { ModelBridgeInternal.setQueryRequestOptionsContinuationToken(cosmosQueryRequestOptions, pagedFluxOptions.getRequestContinuation()); } if (pagedFluxOptions.getMaxItemCount() != null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions.getMaxItemCount()); } else { ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .applyMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions); if (pagedFluxOptions.getMaxItemCount() == null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount( cosmosQueryRequestOptions, Constants.Properties.DEFAULT_MAX_PAGE_SIZE); pagedFluxOptions.setMaxItemCount(Constants.Properties.DEFAULT_MAX_PAGE_SIZE); } } } public static CosmosChangeFeedRequestOptions getEffectiveCosmosChangeFeedRequestOptions( CosmosPagedFluxOptions pagedFluxOptions, CosmosChangeFeedRequestOptions cosmosChangeFeedRequestRequestOptions) { checkNotNull( cosmosChangeFeedRequestRequestOptions, "Argument 'cosmosChangeFeedRequestRequestOptions' must not be null"); return ModelBridgeInternal .getEffectiveChangeFeedRequestOptions( cosmosChangeFeedRequestRequestOptions, pagedFluxOptions); } static String escapeNonAscii(String partitionKeyJson) { StringBuilder sb = null; for (int i = 0; i < partitionKeyJson.length(); i++) { int val = partitionKeyJson.charAt(i); if (val > 127) { if (sb == null) { sb = new StringBuilder(partitionKeyJson.length()); sb.append(partitionKeyJson, 0, i); } sb.append("\\u").append(String.format("%04X", val)); } else { if (sb != null) { sb.append(partitionKeyJson.charAt(i)); } } } if (sb == null) { return partitionKeyJson; } else { return sb.toString(); } } public static byte[] toByteArray(ByteBuf buf) { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); return bytes; } public static String toJson(ObjectMapper mapper, ObjectNode object) { try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert JSON to STRING", e); } } public static long getMaxIntegratedCacheStalenessInMillis(DedicatedGatewayRequestOptions dedicatedGatewayRequestOptions) { Duration maxIntegratedCacheStaleness = dedicatedGatewayRequestOptions.getMaxIntegratedCacheStaleness(); if (maxIntegratedCacheStaleness.toNanos() > 0 && maxIntegratedCacheStaleness.toMillis() <= 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness granularity is milliseconds"); } if (maxIntegratedCacheStaleness.toMillis() < 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness duration cannot be negative"); } return maxIntegratedCacheStaleness.toMillis(); } }
class Utils { private final static Logger logger = LoggerFactory.getLogger(Utils.class); private static final int JAVA_VERSION = getJavaVersion(); private static final int ONE_KB = 1024; private static final ZoneId GMT_ZONE_ID = ZoneId.of("GMT"); public static final Base64.Encoder Base64Encoder = Base64.getEncoder(); public static final Base64.Decoder Base64Decoder = Base64.getDecoder(); public static final Base64.Encoder Base64UrlEncoder = Base64.getUrlEncoder(); private static final ObjectMapper simpleObjectMapperAllowingDuplicatedProperties = createAndInitializeObjectMapper(true); private static final ObjectMapper simpleObjectMapperDisallowingDuplicatedProperties = createAndInitializeObjectMapper(false); private static final ObjectMapper durationEnabledObjectMapper = createAndInitializeDurationObjectMapper(); private static ObjectMapper simpleObjectMapper = simpleObjectMapperDisallowingDuplicatedProperties; private static final TimeBasedGenerator TIME_BASED_GENERATOR = Generators.timeBasedGenerator(EthernetAddress.constructMulticastAddress()); private static final Pattern SPACE_PATTERN = Pattern.compile("\\s"); private static final DateTimeFormatter RFC_1123_DATE_TIME = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); private static ObjectMapper createAndInitializeObjectMapper(boolean allowDuplicateProperties) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); if (!allowDuplicateProperties) { objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); } objectMapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false); if (JAVA_VERSION != -1 && JAVA_VERSION < 16) { objectMapper.registerModule(new AfterburnerModule()); } objectMapper.registerModule(new JavaTimeModule()); return objectMapper; } private static int getJavaVersion() { int version = -1; try { String completeJavaVersion = System.getProperty("java.version"); String[] versionElements = completeJavaVersion.split("\\."); int versionFirstPart = Integer.parseInt(versionElements[0]); if (versionFirstPart == 1) { version = Integer.parseInt(versionElements[1]); } else { version = versionFirstPart; } return version; } catch (Exception ex) { logger.warn("Error while fetching java version", ex); return version; } } public static byte[] getUTF8BytesOrNull(String str) { if (str == null) { return null; } return str.getBytes(StandardCharsets.UTF_8); } public static byte[] getUTF8Bytes(String str) { return str.getBytes(StandardCharsets.UTF_8); } public static String encodeBase64String(byte[] binaryData) { String encodedString = Base64Encoder.encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static String decodeBase64String(String encodedString) { byte[] decodeString = Base64Decoder.decode(encodedString); return new String(decodeString, StandardCharsets.UTF_8); } public static String decodeAsUTF8String(String inputString) { if (inputString == null || inputString.isEmpty()) { return inputString; } try { return URLDecoder.decode(inputString, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { logger.warn("Error while decoding input string", e); return inputString; } } public static String encodeUrlBase64String(byte[] binaryData) { String encodedString = Base64UrlEncoder.withoutPadding().encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static void configureSimpleObjectMapper(boolean allowDuplicateProperties) { if (allowDuplicateProperties) { Utils.simpleObjectMapper = Utils.simpleObjectMapperAllowingDuplicatedProperties; } else { Utils.simpleObjectMapper = Utils.simpleObjectMapperDisallowingDuplicatedProperties; } } /** * Joins the specified paths by appropriately padding them with '/' * * @param path1 the first path segment to join. * @param path2 the second path segment to join. * @return the concatenated path with '/' */ public static String joinPath(String path1, String path2) { path1 = trimBeginningAndEndingSlashes(path1); String result = "/" + path1 + "/"; if (!StringUtils.isEmpty(path2)) { path2 = trimBeginningAndEndingSlashes(path2); result += path2 + "/"; } return result; } /** * Trims the beginning and ending '/' from the given path * * @param path the path to trim for beginning and ending slashes * @return the path without beginning and ending '/' */ public static String trimBeginningAndEndingSlashes(String path) { if(path == null) { return null; } if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path; } public static String createQuery(Map<String, String> queryParameters) { if (queryParameters == null) return ""; StringBuilder queryString = new StringBuilder(); for (Map.Entry<String, String> nameValuePair : queryParameters.entrySet()) { String key = nameValuePair.getKey(); String value = nameValuePair.getValue(); if (key != null && !key.isEmpty()) { if (queryString.length() > 0) { queryString.append(RuntimeConstants.Separators.Query[1]); } queryString.append(key); if (value != null) { queryString.append(RuntimeConstants.Separators.Query[2]); queryString.append(value); } } } return queryString.toString(); } public static URI setQuery(String urlString, String query) { if (urlString == null) throw new IllegalStateException("urlString parameter can't be null."); query = Utils.removeLeadingQuestionMark(query); try { if (query != null && !query.isEmpty()) { return new URI(Utils.addTrailingSlash(urlString) + RuntimeConstants.Separators.Query[0] + query); } else { return new URI(Utils.addTrailingSlash(urlString)); } } catch (URISyntaxException e) { throw new IllegalStateException("Uri is invalid: ", e); } } /** * Given the full path to a resource, extract the collection path. * * @param resourceFullName the full path to the resource. * @return the path of the collection in which the resource is. */ public static String getCollectionName(String resourceFullName) { if (resourceFullName != null) { resourceFullName = Utils.trimBeginningAndEndingSlashes(resourceFullName); int slashCount = 0; for (int i = 0; i < resourceFullName.length(); i++) { if (resourceFullName.charAt(i) == '/') { slashCount++; if (slashCount == 4) { return resourceFullName.substring(0, i); } } } } return resourceFullName; } public static <T> int getCollectionSize(Collection<T> collection) { if (collection == null) { return 0; } return collection.size(); } public static boolean isCollectionChild(ResourceType type) { return type == ResourceType.Document || type == ResourceType.Attachment || type == ResourceType.Conflict || type == ResourceType.StoredProcedure || type == ResourceType.Trigger || type == ResourceType.UserDefinedFunction; } public static boolean isWriteOperation(OperationType operationType) { return operationType == OperationType.Create || operationType == OperationType.Upsert || operationType == OperationType.Delete || operationType == OperationType.Replace || operationType == OperationType.ExecuteJavaScript || operationType == OperationType.Batch; } private static String addTrailingSlash(String path) { if (path == null || path.isEmpty()) path = new String(RuntimeConstants.Separators.Url); else if (path.charAt(path.length() - 1) != RuntimeConstants.Separators.Url[0]) path = path + RuntimeConstants.Separators.Url[0]; return path; } private static String removeLeadingQuestionMark(String path) { if (path == null || path.isEmpty()) return path; if (path.charAt(0) == RuntimeConstants.Separators.Query[0]) return path.substring(1); return path; } public static boolean isValidConsistency(ConsistencyLevel backendConsistency, ConsistencyLevel desiredConsistency) { switch (backendConsistency) { case STRONG: return desiredConsistency == ConsistencyLevel.STRONG || desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case BOUNDED_STALENESS: return desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case SESSION: case EVENTUAL: case CONSISTENT_PREFIX: return desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; default: throw new IllegalArgumentException("backendConsistency"); } } public static String getUserAgent() { return getUserAgent(HttpConstants.Versions.SDK_NAME, HttpConstants.Versions.getSdkVersion()); } public static String getUserAgent(String sdkName, String sdkVersion) { String osName = System.getProperty("os.name"); if (osName == null) { osName = "Unknown"; } osName = SPACE_PATTERN.matcher(osName).replaceAll(""); return String.format("%s%s/%s %s/%s JRE/%s", UserAgentContainer.AZSDK_USERAGENT_PREFIX, sdkName, sdkVersion, osName, System.getProperty("os.version"), System.getProperty("java.version") ); } public static ObjectMapper getSimpleObjectMapper() { return Utils.simpleObjectMapper; } public static ObjectMapper getDurationEnabledObjectMapper() { return durationEnabledObjectMapper; } /** * Returns Current Time in RFC 1123 format, e.g, * Fri, 01 Dec 2017 19:22:30 GMT. * * @return an instance of STRING */ public static String nowAsRFC1123() { ZonedDateTime now = ZonedDateTime.now(GMT_ZONE_ID); return Utils.RFC_1123_DATE_TIME.format(now); } public static UUID randomUUID() { return TIME_BASED_GENERATOR.generate(); } public static String instantAsUTCRFC1123(Instant instant){ return Utils.RFC_1123_DATE_TIME.format(instant.atZone(GMT_ZONE_ID)); } public static int getValueOrDefault(Integer val, int defaultValue) { return val != null ? val : defaultValue; } public static void checkStateOrThrow(boolean value, String argumentName, String message) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, message); if (t != null) { throw t; } } public static void checkNotNullOrThrow(Object val, String argumentName, String message) throws NullPointerException { NullPointerException t = checkNotNullOrReturnException(val, argumentName, message); if (t != null) { throw t; } } public static void checkStateOrThrow(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, argumentName, messageTemplateParams); if (t != null) { throw t; } } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String message) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, message)); } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } private static NullPointerException checkNotNullOrReturnException(Object val, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (val != null) { return null; } return new NullPointerException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } @SuppressWarnings("unchecked") public static <O, I> O as(I i, Class<O> klass) { if (i == null) { return null; } if (klass.isInstance(i)) { return (O) i; } else { return null; } } @SuppressWarnings("unchecked") public static <V> List<V> immutableListOf() { return Collections.EMPTY_LIST; } public static <K, V> Map<K, V>immutableMapOf(K k1, V v1) { Map<K, V> map = new HashMap<>(); map.put(k1, v1); map = Collections.unmodifiableMap(map); return map; } public static <V> V firstOrDefault(List<V> list) { return list.size() > 0? list.get(0) : null ; } public static class ValueHolder<V> { public ValueHolder() { } public ValueHolder(V v) { this.v = v; } public V v; public static <T> ValueHolder<T> initialize(T v) { return new ValueHolder<>(v); } } public static <K, V> boolean tryGetValue(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.get(key); return holder.v != null; } public static <K, V> boolean tryRemove(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.remove(key); return holder.v != null; } public static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) { if (StringUtils.isEmpty(itemResponseBodyAsString)) { return null; } try { return getSimpleObjectMapper().readValue(itemResponseBodyAsString, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse string [%s] to POJO.", itemResponseBodyAsString), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType) { if (Utils.isEmpty(item)) { return null; } try { return getSimpleObjectMapper().readValue(item, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse byte-array %s to POJO.", Arrays.toString(item)), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType, ItemDeserializer itemDeserializer) { if (Utils.isEmpty(item)) { return null; } if (itemDeserializer == null) { return Utils.parse(item, itemClassType); } return itemDeserializer.parseFrom(itemClassType, item); } public static ByteBuffer serializeJsonToByteBuffer(ObjectMapper objectMapper, Object object) { try { ByteBufferOutputStream byteBufferOutputStream = new ByteBufferOutputStream(ONE_KB); objectMapper.writeValue(byteBufferOutputStream, object); return byteBufferOutputStream.asByteBuffer(); } catch (IOException e) { throw new IllegalArgumentException("Failed to serialize the object into json", e); } } public static boolean isEmpty(byte[] bytes) { return bytes == null || bytes.length == 0; } public static String utf8StringFromOrNull(byte[] bytes) { if (bytes == null) { return null; } return new String(bytes, StandardCharsets.UTF_8); } public static void setContinuationTokenAndMaxItemCount(CosmosPagedFluxOptions pagedFluxOptions, CosmosQueryRequestOptions cosmosQueryRequestOptions) { if (pagedFluxOptions == null) { return; } if (pagedFluxOptions.getRequestContinuation() != null) { ModelBridgeInternal.setQueryRequestOptionsContinuationToken(cosmosQueryRequestOptions, pagedFluxOptions.getRequestContinuation()); } if (pagedFluxOptions.getMaxItemCount() != null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions.getMaxItemCount()); } else { ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .applyMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions); if (pagedFluxOptions.getMaxItemCount() == null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount( cosmosQueryRequestOptions, Constants.Properties.DEFAULT_MAX_PAGE_SIZE); pagedFluxOptions.setMaxItemCount(Constants.Properties.DEFAULT_MAX_PAGE_SIZE); } } } public static CosmosChangeFeedRequestOptions getEffectiveCosmosChangeFeedRequestOptions( CosmosPagedFluxOptions pagedFluxOptions, CosmosChangeFeedRequestOptions cosmosChangeFeedRequestRequestOptions) { checkNotNull( cosmosChangeFeedRequestRequestOptions, "Argument 'cosmosChangeFeedRequestRequestOptions' must not be null"); return ModelBridgeInternal .getEffectiveChangeFeedRequestOptions( cosmosChangeFeedRequestRequestOptions, pagedFluxOptions); } static String escapeNonAscii(String partitionKeyJson) { StringBuilder sb = null; for (int i = 0; i < partitionKeyJson.length(); i++) { int val = partitionKeyJson.charAt(i); if (val > 127) { if (sb == null) { sb = new StringBuilder(partitionKeyJson.length()); sb.append(partitionKeyJson, 0, i); } sb.append("\\u").append(String.format("%04X", val)); } else { if (sb != null) { sb.append(partitionKeyJson.charAt(i)); } } } if (sb == null) { return partitionKeyJson; } else { return sb.toString(); } } public static byte[] toByteArray(ByteBuf buf) { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); return bytes; } public static String toJson(ObjectMapper mapper, ObjectNode object) { try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert JSON to STRING", e); } } public static long getMaxIntegratedCacheStalenessInMillis(DedicatedGatewayRequestOptions dedicatedGatewayRequestOptions) { Duration maxIntegratedCacheStaleness = dedicatedGatewayRequestOptions.getMaxIntegratedCacheStaleness(); if (maxIntegratedCacheStaleness.toNanos() > 0 && maxIntegratedCacheStaleness.toMillis() <= 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness granularity is milliseconds"); } if (maxIntegratedCacheStaleness.toMillis() < 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness duration cannot be negative"); } return maxIntegratedCacheStaleness.toMillis(); } }
```suggestion return durationEnabledObjectMapper; ```
public static ObjectMapper getDurationEnabledObjectMapper() { return Utils.durationEnabledObjectMapper; }
return Utils.durationEnabledObjectMapper;
public static ObjectMapper getDurationEnabledObjectMapper() { return durationEnabledObjectMapper; }
class Utils { private final static Logger logger = LoggerFactory.getLogger(Utils.class); private static final int JAVA_VERSION = getJavaVersion(); private static final int ONE_KB = 1024; private static final ZoneId GMT_ZONE_ID = ZoneId.of("GMT"); public static final Base64.Encoder Base64Encoder = Base64.getEncoder(); public static final Base64.Decoder Base64Decoder = Base64.getDecoder(); public static final Base64.Encoder Base64UrlEncoder = Base64.getUrlEncoder(); private static final ObjectMapper simpleObjectMapperAllowingDuplicatedProperties = createAndInitializeObjectMapper(true); private static final ObjectMapper simpleObjectMapperDisallowingDuplicatedProperties = createAndInitializeObjectMapper(false); private static final ObjectMapper durationEnabledObjectMapper = createAndInitializeDurationObjectMapper(); private static ObjectMapper simpleObjectMapper = simpleObjectMapperDisallowingDuplicatedProperties; private static final TimeBasedGenerator TIME_BASED_GENERATOR = Generators.timeBasedGenerator(EthernetAddress.constructMulticastAddress()); private static final Pattern SPACE_PATTERN = Pattern.compile("\\s"); private static final DateTimeFormatter RFC_1123_DATE_TIME = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); private static ObjectMapper createAndInitializeObjectMapper(boolean allowDuplicateProperties) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); if (!allowDuplicateProperties) { objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); } objectMapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false); if (JAVA_VERSION != -1 && JAVA_VERSION < 16) { objectMapper.registerModule(new AfterburnerModule()); } objectMapper.registerModule(new JavaTimeModule()); return objectMapper; } private static ObjectMapper createAndInitializeDurationObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); SimpleFilterProvider filterProvider = new SimpleFilterProvider(); objectMapper.registerModule(new SimpleModule() .addSerializer(Duration.class, ToStringSerializer.instance) .addDeserializer(Duration.class, DurationDeserializer.INSTANCE) .addSerializer(Instant.class, ToStringSerializer.instance)) .setFilterProvider(filterProvider); return objectMapper; } private static int getJavaVersion() { int version = -1; try { String completeJavaVersion = System.getProperty("java.version"); String[] versionElements = completeJavaVersion.split("\\."); int versionFirstPart = Integer.parseInt(versionElements[0]); if (versionFirstPart == 1) { version = Integer.parseInt(versionElements[1]); } else { version = versionFirstPart; } return version; } catch (Exception ex) { logger.warn("Error while fetching java version", ex); return version; } } public static byte[] getUTF8BytesOrNull(String str) { if (str == null) { return null; } return str.getBytes(StandardCharsets.UTF_8); } public static byte[] getUTF8Bytes(String str) { return str.getBytes(StandardCharsets.UTF_8); } public static String encodeBase64String(byte[] binaryData) { String encodedString = Base64Encoder.encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static String decodeBase64String(String encodedString) { byte[] decodeString = Base64Decoder.decode(encodedString); return new String(decodeString, StandardCharsets.UTF_8); } public static String decodeAsUTF8String(String inputString) { if (inputString == null || inputString.isEmpty()) { return inputString; } try { return URLDecoder.decode(inputString, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { logger.warn("Error while decoding input string", e); return inputString; } } public static String encodeUrlBase64String(byte[] binaryData) { String encodedString = Base64UrlEncoder.withoutPadding().encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static void configureSimpleObjectMapper(boolean allowDuplicateProperties) { if (allowDuplicateProperties) { Utils.simpleObjectMapper = Utils.simpleObjectMapperAllowingDuplicatedProperties; } else { Utils.simpleObjectMapper = Utils.simpleObjectMapperDisallowingDuplicatedProperties; } } /** * Joins the specified paths by appropriately padding them with '/' * * @param path1 the first path segment to join. * @param path2 the second path segment to join. * @return the concatenated path with '/' */ public static String joinPath(String path1, String path2) { path1 = trimBeginningAndEndingSlashes(path1); String result = "/" + path1 + "/"; if (!StringUtils.isEmpty(path2)) { path2 = trimBeginningAndEndingSlashes(path2); result += path2 + "/"; } return result; } /** * Trims the beginning and ending '/' from the given path * * @param path the path to trim for beginning and ending slashes * @return the path without beginning and ending '/' */ public static String trimBeginningAndEndingSlashes(String path) { if(path == null) { return null; } if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path; } public static String createQuery(Map<String, String> queryParameters) { if (queryParameters == null) return ""; StringBuilder queryString = new StringBuilder(); for (Map.Entry<String, String> nameValuePair : queryParameters.entrySet()) { String key = nameValuePair.getKey(); String value = nameValuePair.getValue(); if (key != null && !key.isEmpty()) { if (queryString.length() > 0) { queryString.append(RuntimeConstants.Separators.Query[1]); } queryString.append(key); if (value != null) { queryString.append(RuntimeConstants.Separators.Query[2]); queryString.append(value); } } } return queryString.toString(); } public static URI setQuery(String urlString, String query) { if (urlString == null) throw new IllegalStateException("urlString parameter can't be null."); query = Utils.removeLeadingQuestionMark(query); try { if (query != null && !query.isEmpty()) { return new URI(Utils.addTrailingSlash(urlString) + RuntimeConstants.Separators.Query[0] + query); } else { return new URI(Utils.addTrailingSlash(urlString)); } } catch (URISyntaxException e) { throw new IllegalStateException("Uri is invalid: ", e); } } /** * Given the full path to a resource, extract the collection path. * * @param resourceFullName the full path to the resource. * @return the path of the collection in which the resource is. */ public static String getCollectionName(String resourceFullName) { if (resourceFullName != null) { resourceFullName = Utils.trimBeginningAndEndingSlashes(resourceFullName); int slashCount = 0; for (int i = 0; i < resourceFullName.length(); i++) { if (resourceFullName.charAt(i) == '/') { slashCount++; if (slashCount == 4) { return resourceFullName.substring(0, i); } } } } return resourceFullName; } public static <T> int getCollectionSize(Collection<T> collection) { if (collection == null) { return 0; } return collection.size(); } public static boolean isCollectionChild(ResourceType type) { return type == ResourceType.Document || type == ResourceType.Attachment || type == ResourceType.Conflict || type == ResourceType.StoredProcedure || type == ResourceType.Trigger || type == ResourceType.UserDefinedFunction; } public static boolean isWriteOperation(OperationType operationType) { return operationType == OperationType.Create || operationType == OperationType.Upsert || operationType == OperationType.Delete || operationType == OperationType.Replace || operationType == OperationType.ExecuteJavaScript || operationType == OperationType.Batch; } private static String addTrailingSlash(String path) { if (path == null || path.isEmpty()) path = new String(RuntimeConstants.Separators.Url); else if (path.charAt(path.length() - 1) != RuntimeConstants.Separators.Url[0]) path = path + RuntimeConstants.Separators.Url[0]; return path; } private static String removeLeadingQuestionMark(String path) { if (path == null || path.isEmpty()) return path; if (path.charAt(0) == RuntimeConstants.Separators.Query[0]) return path.substring(1); return path; } public static boolean isValidConsistency(ConsistencyLevel backendConsistency, ConsistencyLevel desiredConsistency) { switch (backendConsistency) { case STRONG: return desiredConsistency == ConsistencyLevel.STRONG || desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case BOUNDED_STALENESS: return desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case SESSION: case EVENTUAL: case CONSISTENT_PREFIX: return desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; default: throw new IllegalArgumentException("backendConsistency"); } } public static String getUserAgent() { return getUserAgent(HttpConstants.Versions.SDK_NAME, HttpConstants.Versions.getSdkVersion()); } public static String getUserAgent(String sdkName, String sdkVersion) { String osName = System.getProperty("os.name"); if (osName == null) { osName = "Unknown"; } osName = SPACE_PATTERN.matcher(osName).replaceAll(""); return String.format("%s%s/%s %s/%s JRE/%s", UserAgentContainer.AZSDK_USERAGENT_PREFIX, sdkName, sdkVersion, osName, System.getProperty("os.version"), System.getProperty("java.version") ); } public static ObjectMapper getSimpleObjectMapper() { return Utils.simpleObjectMapper; } /** * Returns Current Time in RFC 1123 format, e.g, * Fri, 01 Dec 2017 19:22:30 GMT. * * @return an instance of STRING */ public static String nowAsRFC1123() { ZonedDateTime now = ZonedDateTime.now(GMT_ZONE_ID); return Utils.RFC_1123_DATE_TIME.format(now); } public static UUID randomUUID() { return TIME_BASED_GENERATOR.generate(); } public static String instantAsUTCRFC1123(Instant instant){ return Utils.RFC_1123_DATE_TIME.format(instant.atZone(GMT_ZONE_ID)); } public static int getValueOrDefault(Integer val, int defaultValue) { return val != null ? val : defaultValue; } public static void checkStateOrThrow(boolean value, String argumentName, String message) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, message); if (t != null) { throw t; } } public static void checkNotNullOrThrow(Object val, String argumentName, String message) throws NullPointerException { NullPointerException t = checkNotNullOrReturnException(val, argumentName, message); if (t != null) { throw t; } } public static void checkStateOrThrow(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, argumentName, messageTemplateParams); if (t != null) { throw t; } } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String message) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, message)); } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } private static NullPointerException checkNotNullOrReturnException(Object val, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (val != null) { return null; } return new NullPointerException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } @SuppressWarnings("unchecked") public static <O, I> O as(I i, Class<O> klass) { if (i == null) { return null; } if (klass.isInstance(i)) { return (O) i; } else { return null; } } @SuppressWarnings("unchecked") public static <V> List<V> immutableListOf() { return Collections.EMPTY_LIST; } public static <K, V> Map<K, V>immutableMapOf(K k1, V v1) { Map<K, V> map = new HashMap<>(); map.put(k1, v1); map = Collections.unmodifiableMap(map); return map; } public static <V> V firstOrDefault(List<V> list) { return list.size() > 0? list.get(0) : null ; } public static class ValueHolder<V> { public ValueHolder() { } public ValueHolder(V v) { this.v = v; } public V v; public static <T> ValueHolder<T> initialize(T v) { return new ValueHolder<>(v); } } public static <K, V> boolean tryGetValue(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.get(key); return holder.v != null; } public static <K, V> boolean tryRemove(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.remove(key); return holder.v != null; } public static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) { if (StringUtils.isEmpty(itemResponseBodyAsString)) { return null; } try { return getSimpleObjectMapper().readValue(itemResponseBodyAsString, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse string [%s] to POJO.", itemResponseBodyAsString), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType) { if (Utils.isEmpty(item)) { return null; } try { return getSimpleObjectMapper().readValue(item, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse byte-array %s to POJO.", Arrays.toString(item)), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType, ItemDeserializer itemDeserializer) { if (Utils.isEmpty(item)) { return null; } if (itemDeserializer == null) { return Utils.parse(item, itemClassType); } return itemDeserializer.parseFrom(itemClassType, item); } public static ByteBuffer serializeJsonToByteBuffer(ObjectMapper objectMapper, Object object) { try { ByteBufferOutputStream byteBufferOutputStream = new ByteBufferOutputStream(ONE_KB); objectMapper.writeValue(byteBufferOutputStream, object); return byteBufferOutputStream.asByteBuffer(); } catch (IOException e) { throw new IllegalArgumentException("Failed to serialize the object into json", e); } } public static boolean isEmpty(byte[] bytes) { return bytes == null || bytes.length == 0; } public static String utf8StringFromOrNull(byte[] bytes) { if (bytes == null) { return null; } return new String(bytes, StandardCharsets.UTF_8); } public static void setContinuationTokenAndMaxItemCount(CosmosPagedFluxOptions pagedFluxOptions, CosmosQueryRequestOptions cosmosQueryRequestOptions) { if (pagedFluxOptions == null) { return; } if (pagedFluxOptions.getRequestContinuation() != null) { ModelBridgeInternal.setQueryRequestOptionsContinuationToken(cosmosQueryRequestOptions, pagedFluxOptions.getRequestContinuation()); } if (pagedFluxOptions.getMaxItemCount() != null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions.getMaxItemCount()); } else { ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .applyMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions); if (pagedFluxOptions.getMaxItemCount() == null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount( cosmosQueryRequestOptions, Constants.Properties.DEFAULT_MAX_PAGE_SIZE); pagedFluxOptions.setMaxItemCount(Constants.Properties.DEFAULT_MAX_PAGE_SIZE); } } } public static CosmosChangeFeedRequestOptions getEffectiveCosmosChangeFeedRequestOptions( CosmosPagedFluxOptions pagedFluxOptions, CosmosChangeFeedRequestOptions cosmosChangeFeedRequestRequestOptions) { checkNotNull( cosmosChangeFeedRequestRequestOptions, "Argument 'cosmosChangeFeedRequestRequestOptions' must not be null"); return ModelBridgeInternal .getEffectiveChangeFeedRequestOptions( cosmosChangeFeedRequestRequestOptions, pagedFluxOptions); } static String escapeNonAscii(String partitionKeyJson) { StringBuilder sb = null; for (int i = 0; i < partitionKeyJson.length(); i++) { int val = partitionKeyJson.charAt(i); if (val > 127) { if (sb == null) { sb = new StringBuilder(partitionKeyJson.length()); sb.append(partitionKeyJson, 0, i); } sb.append("\\u").append(String.format("%04X", val)); } else { if (sb != null) { sb.append(partitionKeyJson.charAt(i)); } } } if (sb == null) { return partitionKeyJson; } else { return sb.toString(); } } public static byte[] toByteArray(ByteBuf buf) { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); return bytes; } public static String toJson(ObjectMapper mapper, ObjectNode object) { try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert JSON to STRING", e); } } public static long getMaxIntegratedCacheStalenessInMillis(DedicatedGatewayRequestOptions dedicatedGatewayRequestOptions) { Duration maxIntegratedCacheStaleness = dedicatedGatewayRequestOptions.getMaxIntegratedCacheStaleness(); if (maxIntegratedCacheStaleness.toNanos() > 0 && maxIntegratedCacheStaleness.toMillis() <= 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness granularity is milliseconds"); } if (maxIntegratedCacheStaleness.toMillis() < 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness duration cannot be negative"); } return maxIntegratedCacheStaleness.toMillis(); } }
class Utils { private final static Logger logger = LoggerFactory.getLogger(Utils.class); private static final int JAVA_VERSION = getJavaVersion(); private static final int ONE_KB = 1024; private static final ZoneId GMT_ZONE_ID = ZoneId.of("GMT"); public static final Base64.Encoder Base64Encoder = Base64.getEncoder(); public static final Base64.Decoder Base64Decoder = Base64.getDecoder(); public static final Base64.Encoder Base64UrlEncoder = Base64.getUrlEncoder(); private static final ObjectMapper simpleObjectMapperAllowingDuplicatedProperties = createAndInitializeObjectMapper(true); private static final ObjectMapper simpleObjectMapperDisallowingDuplicatedProperties = createAndInitializeObjectMapper(false); private static final ObjectMapper durationEnabledObjectMapper = createAndInitializeDurationObjectMapper(); private static ObjectMapper simpleObjectMapper = simpleObjectMapperDisallowingDuplicatedProperties; private static final TimeBasedGenerator TIME_BASED_GENERATOR = Generators.timeBasedGenerator(EthernetAddress.constructMulticastAddress()); private static final Pattern SPACE_PATTERN = Pattern.compile("\\s"); private static final DateTimeFormatter RFC_1123_DATE_TIME = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); private static ObjectMapper createAndInitializeObjectMapper(boolean allowDuplicateProperties) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); if (!allowDuplicateProperties) { objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); } objectMapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false); if (JAVA_VERSION != -1 && JAVA_VERSION < 16) { objectMapper.registerModule(new AfterburnerModule()); } objectMapper.registerModule(new JavaTimeModule()); return objectMapper; } private static ObjectMapper createAndInitializeDurationObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new SimpleModule() .addSerializer(Duration.class, ToStringSerializer.instance) .addSerializer(Instant.class, ToStringSerializer.instance)); return objectMapper; } private static int getJavaVersion() { int version = -1; try { String completeJavaVersion = System.getProperty("java.version"); String[] versionElements = completeJavaVersion.split("\\."); int versionFirstPart = Integer.parseInt(versionElements[0]); if (versionFirstPart == 1) { version = Integer.parseInt(versionElements[1]); } else { version = versionFirstPart; } return version; } catch (Exception ex) { logger.warn("Error while fetching java version", ex); return version; } } public static byte[] getUTF8BytesOrNull(String str) { if (str == null) { return null; } return str.getBytes(StandardCharsets.UTF_8); } public static byte[] getUTF8Bytes(String str) { return str.getBytes(StandardCharsets.UTF_8); } public static String encodeBase64String(byte[] binaryData) { String encodedString = Base64Encoder.encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static String decodeBase64String(String encodedString) { byte[] decodeString = Base64Decoder.decode(encodedString); return new String(decodeString, StandardCharsets.UTF_8); } public static String decodeAsUTF8String(String inputString) { if (inputString == null || inputString.isEmpty()) { return inputString; } try { return URLDecoder.decode(inputString, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { logger.warn("Error while decoding input string", e); return inputString; } } public static String encodeUrlBase64String(byte[] binaryData) { String encodedString = Base64UrlEncoder.withoutPadding().encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static void configureSimpleObjectMapper(boolean allowDuplicateProperties) { if (allowDuplicateProperties) { Utils.simpleObjectMapper = Utils.simpleObjectMapperAllowingDuplicatedProperties; } else { Utils.simpleObjectMapper = Utils.simpleObjectMapperDisallowingDuplicatedProperties; } } /** * Joins the specified paths by appropriately padding them with '/' * * @param path1 the first path segment to join. * @param path2 the second path segment to join. * @return the concatenated path with '/' */ public static String joinPath(String path1, String path2) { path1 = trimBeginningAndEndingSlashes(path1); String result = "/" + path1 + "/"; if (!StringUtils.isEmpty(path2)) { path2 = trimBeginningAndEndingSlashes(path2); result += path2 + "/"; } return result; } /** * Trims the beginning and ending '/' from the given path * * @param path the path to trim for beginning and ending slashes * @return the path without beginning and ending '/' */ public static String trimBeginningAndEndingSlashes(String path) { if(path == null) { return null; } if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path; } public static String createQuery(Map<String, String> queryParameters) { if (queryParameters == null) return ""; StringBuilder queryString = new StringBuilder(); for (Map.Entry<String, String> nameValuePair : queryParameters.entrySet()) { String key = nameValuePair.getKey(); String value = nameValuePair.getValue(); if (key != null && !key.isEmpty()) { if (queryString.length() > 0) { queryString.append(RuntimeConstants.Separators.Query[1]); } queryString.append(key); if (value != null) { queryString.append(RuntimeConstants.Separators.Query[2]); queryString.append(value); } } } return queryString.toString(); } public static URI setQuery(String urlString, String query) { if (urlString == null) throw new IllegalStateException("urlString parameter can't be null."); query = Utils.removeLeadingQuestionMark(query); try { if (query != null && !query.isEmpty()) { return new URI(Utils.addTrailingSlash(urlString) + RuntimeConstants.Separators.Query[0] + query); } else { return new URI(Utils.addTrailingSlash(urlString)); } } catch (URISyntaxException e) { throw new IllegalStateException("Uri is invalid: ", e); } } /** * Given the full path to a resource, extract the collection path. * * @param resourceFullName the full path to the resource. * @return the path of the collection in which the resource is. */ public static String getCollectionName(String resourceFullName) { if (resourceFullName != null) { resourceFullName = Utils.trimBeginningAndEndingSlashes(resourceFullName); int slashCount = 0; for (int i = 0; i < resourceFullName.length(); i++) { if (resourceFullName.charAt(i) == '/') { slashCount++; if (slashCount == 4) { return resourceFullName.substring(0, i); } } } } return resourceFullName; } public static <T> int getCollectionSize(Collection<T> collection) { if (collection == null) { return 0; } return collection.size(); } public static boolean isCollectionChild(ResourceType type) { return type == ResourceType.Document || type == ResourceType.Attachment || type == ResourceType.Conflict || type == ResourceType.StoredProcedure || type == ResourceType.Trigger || type == ResourceType.UserDefinedFunction; } public static boolean isWriteOperation(OperationType operationType) { return operationType == OperationType.Create || operationType == OperationType.Upsert || operationType == OperationType.Delete || operationType == OperationType.Replace || operationType == OperationType.ExecuteJavaScript || operationType == OperationType.Batch; } private static String addTrailingSlash(String path) { if (path == null || path.isEmpty()) path = new String(RuntimeConstants.Separators.Url); else if (path.charAt(path.length() - 1) != RuntimeConstants.Separators.Url[0]) path = path + RuntimeConstants.Separators.Url[0]; return path; } private static String removeLeadingQuestionMark(String path) { if (path == null || path.isEmpty()) return path; if (path.charAt(0) == RuntimeConstants.Separators.Query[0]) return path.substring(1); return path; } public static boolean isValidConsistency(ConsistencyLevel backendConsistency, ConsistencyLevel desiredConsistency) { switch (backendConsistency) { case STRONG: return desiredConsistency == ConsistencyLevel.STRONG || desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case BOUNDED_STALENESS: return desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case SESSION: case EVENTUAL: case CONSISTENT_PREFIX: return desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; default: throw new IllegalArgumentException("backendConsistency"); } } public static String getUserAgent() { return getUserAgent(HttpConstants.Versions.SDK_NAME, HttpConstants.Versions.getSdkVersion()); } public static String getUserAgent(String sdkName, String sdkVersion) { String osName = System.getProperty("os.name"); if (osName == null) { osName = "Unknown"; } osName = SPACE_PATTERN.matcher(osName).replaceAll(""); return String.format("%s%s/%s %s/%s JRE/%s", UserAgentContainer.AZSDK_USERAGENT_PREFIX, sdkName, sdkVersion, osName, System.getProperty("os.version"), System.getProperty("java.version") ); } public static ObjectMapper getSimpleObjectMapper() { return Utils.simpleObjectMapper; } /** * Returns Current Time in RFC 1123 format, e.g, * Fri, 01 Dec 2017 19:22:30 GMT. * * @return an instance of STRING */ public static String nowAsRFC1123() { ZonedDateTime now = ZonedDateTime.now(GMT_ZONE_ID); return Utils.RFC_1123_DATE_TIME.format(now); } public static UUID randomUUID() { return TIME_BASED_GENERATOR.generate(); } public static String instantAsUTCRFC1123(Instant instant){ return Utils.RFC_1123_DATE_TIME.format(instant.atZone(GMT_ZONE_ID)); } public static int getValueOrDefault(Integer val, int defaultValue) { return val != null ? val : defaultValue; } public static void checkStateOrThrow(boolean value, String argumentName, String message) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, message); if (t != null) { throw t; } } public static void checkNotNullOrThrow(Object val, String argumentName, String message) throws NullPointerException { NullPointerException t = checkNotNullOrReturnException(val, argumentName, message); if (t != null) { throw t; } } public static void checkStateOrThrow(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, argumentName, messageTemplateParams); if (t != null) { throw t; } } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String message) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, message)); } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } private static NullPointerException checkNotNullOrReturnException(Object val, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (val != null) { return null; } return new NullPointerException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } @SuppressWarnings("unchecked") public static <O, I> O as(I i, Class<O> klass) { if (i == null) { return null; } if (klass.isInstance(i)) { return (O) i; } else { return null; } } @SuppressWarnings("unchecked") public static <V> List<V> immutableListOf() { return Collections.EMPTY_LIST; } public static <K, V> Map<K, V>immutableMapOf(K k1, V v1) { Map<K, V> map = new HashMap<>(); map.put(k1, v1); map = Collections.unmodifiableMap(map); return map; } public static <V> V firstOrDefault(List<V> list) { return list.size() > 0? list.get(0) : null ; } public static class ValueHolder<V> { public ValueHolder() { } public ValueHolder(V v) { this.v = v; } public V v; public static <T> ValueHolder<T> initialize(T v) { return new ValueHolder<>(v); } } public static <K, V> boolean tryGetValue(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.get(key); return holder.v != null; } public static <K, V> boolean tryRemove(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.remove(key); return holder.v != null; } public static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) { if (StringUtils.isEmpty(itemResponseBodyAsString)) { return null; } try { return getSimpleObjectMapper().readValue(itemResponseBodyAsString, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse string [%s] to POJO.", itemResponseBodyAsString), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType) { if (Utils.isEmpty(item)) { return null; } try { return getSimpleObjectMapper().readValue(item, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse byte-array %s to POJO.", Arrays.toString(item)), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType, ItemDeserializer itemDeserializer) { if (Utils.isEmpty(item)) { return null; } if (itemDeserializer == null) { return Utils.parse(item, itemClassType); } return itemDeserializer.parseFrom(itemClassType, item); } public static ByteBuffer serializeJsonToByteBuffer(ObjectMapper objectMapper, Object object) { try { ByteBufferOutputStream byteBufferOutputStream = new ByteBufferOutputStream(ONE_KB); objectMapper.writeValue(byteBufferOutputStream, object); return byteBufferOutputStream.asByteBuffer(); } catch (IOException e) { throw new IllegalArgumentException("Failed to serialize the object into json", e); } } public static boolean isEmpty(byte[] bytes) { return bytes == null || bytes.length == 0; } public static String utf8StringFromOrNull(byte[] bytes) { if (bytes == null) { return null; } return new String(bytes, StandardCharsets.UTF_8); } public static void setContinuationTokenAndMaxItemCount(CosmosPagedFluxOptions pagedFluxOptions, CosmosQueryRequestOptions cosmosQueryRequestOptions) { if (pagedFluxOptions == null) { return; } if (pagedFluxOptions.getRequestContinuation() != null) { ModelBridgeInternal.setQueryRequestOptionsContinuationToken(cosmosQueryRequestOptions, pagedFluxOptions.getRequestContinuation()); } if (pagedFluxOptions.getMaxItemCount() != null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions.getMaxItemCount()); } else { ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .applyMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions); if (pagedFluxOptions.getMaxItemCount() == null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount( cosmosQueryRequestOptions, Constants.Properties.DEFAULT_MAX_PAGE_SIZE); pagedFluxOptions.setMaxItemCount(Constants.Properties.DEFAULT_MAX_PAGE_SIZE); } } } public static CosmosChangeFeedRequestOptions getEffectiveCosmosChangeFeedRequestOptions( CosmosPagedFluxOptions pagedFluxOptions, CosmosChangeFeedRequestOptions cosmosChangeFeedRequestRequestOptions) { checkNotNull( cosmosChangeFeedRequestRequestOptions, "Argument 'cosmosChangeFeedRequestRequestOptions' must not be null"); return ModelBridgeInternal .getEffectiveChangeFeedRequestOptions( cosmosChangeFeedRequestRequestOptions, pagedFluxOptions); } static String escapeNonAscii(String partitionKeyJson) { StringBuilder sb = null; for (int i = 0; i < partitionKeyJson.length(); i++) { int val = partitionKeyJson.charAt(i); if (val > 127) { if (sb == null) { sb = new StringBuilder(partitionKeyJson.length()); sb.append(partitionKeyJson, 0, i); } sb.append("\\u").append(String.format("%04X", val)); } else { if (sb != null) { sb.append(partitionKeyJson.charAt(i)); } } } if (sb == null) { return partitionKeyJson; } else { return sb.toString(); } } public static byte[] toByteArray(ByteBuf buf) { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); return bytes; } public static String toJson(ObjectMapper mapper, ObjectNode object) { try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert JSON to STRING", e); } } public static long getMaxIntegratedCacheStalenessInMillis(DedicatedGatewayRequestOptions dedicatedGatewayRequestOptions) { Duration maxIntegratedCacheStaleness = dedicatedGatewayRequestOptions.getMaxIntegratedCacheStaleness(); if (maxIntegratedCacheStaleness.toNanos() > 0 && maxIntegratedCacheStaleness.toMillis() <= 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness granularity is milliseconds"); } if (maxIntegratedCacheStaleness.toMillis() < 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness duration cannot be negative"); } return maxIntegratedCacheStaleness.toMillis(); } }
Just curious - the deserializer for `Duration` - is this needed for an `ObjectMapper` instance primarily used in `toString()`? If so, why no deserializer for `Instant`?
private static ObjectMapper createAndInitializeDurationObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); SimpleFilterProvider filterProvider = new SimpleFilterProvider(); objectMapper.registerModule(new SimpleModule() .addSerializer(Duration.class, ToStringSerializer.instance) .addDeserializer(Duration.class, DurationDeserializer.INSTANCE) .addSerializer(Instant.class, ToStringSerializer.instance)) .setFilterProvider(filterProvider); return objectMapper; }
.setFilterProvider(filterProvider);
private static ObjectMapper createAndInitializeDurationObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new SimpleModule() .addSerializer(Duration.class, ToStringSerializer.instance) .addSerializer(Instant.class, ToStringSerializer.instance)); return objectMapper; }
class Utils { private final static Logger logger = LoggerFactory.getLogger(Utils.class); private static final int JAVA_VERSION = getJavaVersion(); private static final int ONE_KB = 1024; private static final ZoneId GMT_ZONE_ID = ZoneId.of("GMT"); public static final Base64.Encoder Base64Encoder = Base64.getEncoder(); public static final Base64.Decoder Base64Decoder = Base64.getDecoder(); public static final Base64.Encoder Base64UrlEncoder = Base64.getUrlEncoder(); private static final ObjectMapper simpleObjectMapperAllowingDuplicatedProperties = createAndInitializeObjectMapper(true); private static final ObjectMapper simpleObjectMapperDisallowingDuplicatedProperties = createAndInitializeObjectMapper(false); private static final ObjectMapper durationEnabledObjectMapper = createAndInitializeDurationObjectMapper(); private static ObjectMapper simpleObjectMapper = simpleObjectMapperDisallowingDuplicatedProperties; private static final TimeBasedGenerator TIME_BASED_GENERATOR = Generators.timeBasedGenerator(EthernetAddress.constructMulticastAddress()); private static final Pattern SPACE_PATTERN = Pattern.compile("\\s"); private static final DateTimeFormatter RFC_1123_DATE_TIME = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); private static ObjectMapper createAndInitializeObjectMapper(boolean allowDuplicateProperties) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); if (!allowDuplicateProperties) { objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); } objectMapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false); if (JAVA_VERSION != -1 && JAVA_VERSION < 16) { objectMapper.registerModule(new AfterburnerModule()); } objectMapper.registerModule(new JavaTimeModule()); return objectMapper; } private static int getJavaVersion() { int version = -1; try { String completeJavaVersion = System.getProperty("java.version"); String[] versionElements = completeJavaVersion.split("\\."); int versionFirstPart = Integer.parseInt(versionElements[0]); if (versionFirstPart == 1) { version = Integer.parseInt(versionElements[1]); } else { version = versionFirstPart; } return version; } catch (Exception ex) { logger.warn("Error while fetching java version", ex); return version; } } public static byte[] getUTF8BytesOrNull(String str) { if (str == null) { return null; } return str.getBytes(StandardCharsets.UTF_8); } public static byte[] getUTF8Bytes(String str) { return str.getBytes(StandardCharsets.UTF_8); } public static String encodeBase64String(byte[] binaryData) { String encodedString = Base64Encoder.encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static String decodeBase64String(String encodedString) { byte[] decodeString = Base64Decoder.decode(encodedString); return new String(decodeString, StandardCharsets.UTF_8); } public static String decodeAsUTF8String(String inputString) { if (inputString == null || inputString.isEmpty()) { return inputString; } try { return URLDecoder.decode(inputString, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { logger.warn("Error while decoding input string", e); return inputString; } } public static String encodeUrlBase64String(byte[] binaryData) { String encodedString = Base64UrlEncoder.withoutPadding().encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static void configureSimpleObjectMapper(boolean allowDuplicateProperties) { if (allowDuplicateProperties) { Utils.simpleObjectMapper = Utils.simpleObjectMapperAllowingDuplicatedProperties; } else { Utils.simpleObjectMapper = Utils.simpleObjectMapperDisallowingDuplicatedProperties; } } /** * Joins the specified paths by appropriately padding them with '/' * * @param path1 the first path segment to join. * @param path2 the second path segment to join. * @return the concatenated path with '/' */ public static String joinPath(String path1, String path2) { path1 = trimBeginningAndEndingSlashes(path1); String result = "/" + path1 + "/"; if (!StringUtils.isEmpty(path2)) { path2 = trimBeginningAndEndingSlashes(path2); result += path2 + "/"; } return result; } /** * Trims the beginning and ending '/' from the given path * * @param path the path to trim for beginning and ending slashes * @return the path without beginning and ending '/' */ public static String trimBeginningAndEndingSlashes(String path) { if(path == null) { return null; } if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path; } public static String createQuery(Map<String, String> queryParameters) { if (queryParameters == null) return ""; StringBuilder queryString = new StringBuilder(); for (Map.Entry<String, String> nameValuePair : queryParameters.entrySet()) { String key = nameValuePair.getKey(); String value = nameValuePair.getValue(); if (key != null && !key.isEmpty()) { if (queryString.length() > 0) { queryString.append(RuntimeConstants.Separators.Query[1]); } queryString.append(key); if (value != null) { queryString.append(RuntimeConstants.Separators.Query[2]); queryString.append(value); } } } return queryString.toString(); } public static URI setQuery(String urlString, String query) { if (urlString == null) throw new IllegalStateException("urlString parameter can't be null."); query = Utils.removeLeadingQuestionMark(query); try { if (query != null && !query.isEmpty()) { return new URI(Utils.addTrailingSlash(urlString) + RuntimeConstants.Separators.Query[0] + query); } else { return new URI(Utils.addTrailingSlash(urlString)); } } catch (URISyntaxException e) { throw new IllegalStateException("Uri is invalid: ", e); } } /** * Given the full path to a resource, extract the collection path. * * @param resourceFullName the full path to the resource. * @return the path of the collection in which the resource is. */ public static String getCollectionName(String resourceFullName) { if (resourceFullName != null) { resourceFullName = Utils.trimBeginningAndEndingSlashes(resourceFullName); int slashCount = 0; for (int i = 0; i < resourceFullName.length(); i++) { if (resourceFullName.charAt(i) == '/') { slashCount++; if (slashCount == 4) { return resourceFullName.substring(0, i); } } } } return resourceFullName; } public static <T> int getCollectionSize(Collection<T> collection) { if (collection == null) { return 0; } return collection.size(); } public static boolean isCollectionChild(ResourceType type) { return type == ResourceType.Document || type == ResourceType.Attachment || type == ResourceType.Conflict || type == ResourceType.StoredProcedure || type == ResourceType.Trigger || type == ResourceType.UserDefinedFunction; } public static boolean isWriteOperation(OperationType operationType) { return operationType == OperationType.Create || operationType == OperationType.Upsert || operationType == OperationType.Delete || operationType == OperationType.Replace || operationType == OperationType.ExecuteJavaScript || operationType == OperationType.Batch; } private static String addTrailingSlash(String path) { if (path == null || path.isEmpty()) path = new String(RuntimeConstants.Separators.Url); else if (path.charAt(path.length() - 1) != RuntimeConstants.Separators.Url[0]) path = path + RuntimeConstants.Separators.Url[0]; return path; } private static String removeLeadingQuestionMark(String path) { if (path == null || path.isEmpty()) return path; if (path.charAt(0) == RuntimeConstants.Separators.Query[0]) return path.substring(1); return path; } public static boolean isValidConsistency(ConsistencyLevel backendConsistency, ConsistencyLevel desiredConsistency) { switch (backendConsistency) { case STRONG: return desiredConsistency == ConsistencyLevel.STRONG || desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case BOUNDED_STALENESS: return desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case SESSION: case EVENTUAL: case CONSISTENT_PREFIX: return desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; default: throw new IllegalArgumentException("backendConsistency"); } } public static String getUserAgent() { return getUserAgent(HttpConstants.Versions.SDK_NAME, HttpConstants.Versions.getSdkVersion()); } public static String getUserAgent(String sdkName, String sdkVersion) { String osName = System.getProperty("os.name"); if (osName == null) { osName = "Unknown"; } osName = SPACE_PATTERN.matcher(osName).replaceAll(""); return String.format("%s%s/%s %s/%s JRE/%s", UserAgentContainer.AZSDK_USERAGENT_PREFIX, sdkName, sdkVersion, osName, System.getProperty("os.version"), System.getProperty("java.version") ); } public static ObjectMapper getSimpleObjectMapper() { return Utils.simpleObjectMapper; } public static ObjectMapper getDurationEnabledObjectMapper() { return Utils.durationEnabledObjectMapper; } /** * Returns Current Time in RFC 1123 format, e.g, * Fri, 01 Dec 2017 19:22:30 GMT. * * @return an instance of STRING */ public static String nowAsRFC1123() { ZonedDateTime now = ZonedDateTime.now(GMT_ZONE_ID); return Utils.RFC_1123_DATE_TIME.format(now); } public static UUID randomUUID() { return TIME_BASED_GENERATOR.generate(); } public static String instantAsUTCRFC1123(Instant instant){ return Utils.RFC_1123_DATE_TIME.format(instant.atZone(GMT_ZONE_ID)); } public static int getValueOrDefault(Integer val, int defaultValue) { return val != null ? val : defaultValue; } public static void checkStateOrThrow(boolean value, String argumentName, String message) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, message); if (t != null) { throw t; } } public static void checkNotNullOrThrow(Object val, String argumentName, String message) throws NullPointerException { NullPointerException t = checkNotNullOrReturnException(val, argumentName, message); if (t != null) { throw t; } } public static void checkStateOrThrow(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, argumentName, messageTemplateParams); if (t != null) { throw t; } } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String message) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, message)); } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } private static NullPointerException checkNotNullOrReturnException(Object val, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (val != null) { return null; } return new NullPointerException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } @SuppressWarnings("unchecked") public static <O, I> O as(I i, Class<O> klass) { if (i == null) { return null; } if (klass.isInstance(i)) { return (O) i; } else { return null; } } @SuppressWarnings("unchecked") public static <V> List<V> immutableListOf() { return Collections.EMPTY_LIST; } public static <K, V> Map<K, V>immutableMapOf(K k1, V v1) { Map<K, V> map = new HashMap<>(); map.put(k1, v1); map = Collections.unmodifiableMap(map); return map; } public static <V> V firstOrDefault(List<V> list) { return list.size() > 0? list.get(0) : null ; } public static class ValueHolder<V> { public ValueHolder() { } public ValueHolder(V v) { this.v = v; } public V v; public static <T> ValueHolder<T> initialize(T v) { return new ValueHolder<>(v); } } public static <K, V> boolean tryGetValue(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.get(key); return holder.v != null; } public static <K, V> boolean tryRemove(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.remove(key); return holder.v != null; } public static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) { if (StringUtils.isEmpty(itemResponseBodyAsString)) { return null; } try { return getSimpleObjectMapper().readValue(itemResponseBodyAsString, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse string [%s] to POJO.", itemResponseBodyAsString), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType) { if (Utils.isEmpty(item)) { return null; } try { return getSimpleObjectMapper().readValue(item, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse byte-array %s to POJO.", Arrays.toString(item)), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType, ItemDeserializer itemDeserializer) { if (Utils.isEmpty(item)) { return null; } if (itemDeserializer == null) { return Utils.parse(item, itemClassType); } return itemDeserializer.parseFrom(itemClassType, item); } public static ByteBuffer serializeJsonToByteBuffer(ObjectMapper objectMapper, Object object) { try { ByteBufferOutputStream byteBufferOutputStream = new ByteBufferOutputStream(ONE_KB); objectMapper.writeValue(byteBufferOutputStream, object); return byteBufferOutputStream.asByteBuffer(); } catch (IOException e) { throw new IllegalArgumentException("Failed to serialize the object into json", e); } } public static boolean isEmpty(byte[] bytes) { return bytes == null || bytes.length == 0; } public static String utf8StringFromOrNull(byte[] bytes) { if (bytes == null) { return null; } return new String(bytes, StandardCharsets.UTF_8); } public static void setContinuationTokenAndMaxItemCount(CosmosPagedFluxOptions pagedFluxOptions, CosmosQueryRequestOptions cosmosQueryRequestOptions) { if (pagedFluxOptions == null) { return; } if (pagedFluxOptions.getRequestContinuation() != null) { ModelBridgeInternal.setQueryRequestOptionsContinuationToken(cosmosQueryRequestOptions, pagedFluxOptions.getRequestContinuation()); } if (pagedFluxOptions.getMaxItemCount() != null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions.getMaxItemCount()); } else { ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .applyMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions); if (pagedFluxOptions.getMaxItemCount() == null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount( cosmosQueryRequestOptions, Constants.Properties.DEFAULT_MAX_PAGE_SIZE); pagedFluxOptions.setMaxItemCount(Constants.Properties.DEFAULT_MAX_PAGE_SIZE); } } } public static CosmosChangeFeedRequestOptions getEffectiveCosmosChangeFeedRequestOptions( CosmosPagedFluxOptions pagedFluxOptions, CosmosChangeFeedRequestOptions cosmosChangeFeedRequestRequestOptions) { checkNotNull( cosmosChangeFeedRequestRequestOptions, "Argument 'cosmosChangeFeedRequestRequestOptions' must not be null"); return ModelBridgeInternal .getEffectiveChangeFeedRequestOptions( cosmosChangeFeedRequestRequestOptions, pagedFluxOptions); } static String escapeNonAscii(String partitionKeyJson) { StringBuilder sb = null; for (int i = 0; i < partitionKeyJson.length(); i++) { int val = partitionKeyJson.charAt(i); if (val > 127) { if (sb == null) { sb = new StringBuilder(partitionKeyJson.length()); sb.append(partitionKeyJson, 0, i); } sb.append("\\u").append(String.format("%04X", val)); } else { if (sb != null) { sb.append(partitionKeyJson.charAt(i)); } } } if (sb == null) { return partitionKeyJson; } else { return sb.toString(); } } public static byte[] toByteArray(ByteBuf buf) { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); return bytes; } public static String toJson(ObjectMapper mapper, ObjectNode object) { try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert JSON to STRING", e); } } public static long getMaxIntegratedCacheStalenessInMillis(DedicatedGatewayRequestOptions dedicatedGatewayRequestOptions) { Duration maxIntegratedCacheStaleness = dedicatedGatewayRequestOptions.getMaxIntegratedCacheStaleness(); if (maxIntegratedCacheStaleness.toNanos() > 0 && maxIntegratedCacheStaleness.toMillis() <= 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness granularity is milliseconds"); } if (maxIntegratedCacheStaleness.toMillis() < 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness duration cannot be negative"); } return maxIntegratedCacheStaleness.toMillis(); } }
class Utils { private final static Logger logger = LoggerFactory.getLogger(Utils.class); private static final int JAVA_VERSION = getJavaVersion(); private static final int ONE_KB = 1024; private static final ZoneId GMT_ZONE_ID = ZoneId.of("GMT"); public static final Base64.Encoder Base64Encoder = Base64.getEncoder(); public static final Base64.Decoder Base64Decoder = Base64.getDecoder(); public static final Base64.Encoder Base64UrlEncoder = Base64.getUrlEncoder(); private static final ObjectMapper simpleObjectMapperAllowingDuplicatedProperties = createAndInitializeObjectMapper(true); private static final ObjectMapper simpleObjectMapperDisallowingDuplicatedProperties = createAndInitializeObjectMapper(false); private static final ObjectMapper durationEnabledObjectMapper = createAndInitializeDurationObjectMapper(); private static ObjectMapper simpleObjectMapper = simpleObjectMapperDisallowingDuplicatedProperties; private static final TimeBasedGenerator TIME_BASED_GENERATOR = Generators.timeBasedGenerator(EthernetAddress.constructMulticastAddress()); private static final Pattern SPACE_PATTERN = Pattern.compile("\\s"); private static final DateTimeFormatter RFC_1123_DATE_TIME = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); private static ObjectMapper createAndInitializeObjectMapper(boolean allowDuplicateProperties) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); if (!allowDuplicateProperties) { objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); } objectMapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false); if (JAVA_VERSION != -1 && JAVA_VERSION < 16) { objectMapper.registerModule(new AfterburnerModule()); } objectMapper.registerModule(new JavaTimeModule()); return objectMapper; } private static int getJavaVersion() { int version = -1; try { String completeJavaVersion = System.getProperty("java.version"); String[] versionElements = completeJavaVersion.split("\\."); int versionFirstPart = Integer.parseInt(versionElements[0]); if (versionFirstPart == 1) { version = Integer.parseInt(versionElements[1]); } else { version = versionFirstPart; } return version; } catch (Exception ex) { logger.warn("Error while fetching java version", ex); return version; } } public static byte[] getUTF8BytesOrNull(String str) { if (str == null) { return null; } return str.getBytes(StandardCharsets.UTF_8); } public static byte[] getUTF8Bytes(String str) { return str.getBytes(StandardCharsets.UTF_8); } public static String encodeBase64String(byte[] binaryData) { String encodedString = Base64Encoder.encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static String decodeBase64String(String encodedString) { byte[] decodeString = Base64Decoder.decode(encodedString); return new String(decodeString, StandardCharsets.UTF_8); } public static String decodeAsUTF8String(String inputString) { if (inputString == null || inputString.isEmpty()) { return inputString; } try { return URLDecoder.decode(inputString, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { logger.warn("Error while decoding input string", e); return inputString; } } public static String encodeUrlBase64String(byte[] binaryData) { String encodedString = Base64UrlEncoder.withoutPadding().encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static void configureSimpleObjectMapper(boolean allowDuplicateProperties) { if (allowDuplicateProperties) { Utils.simpleObjectMapper = Utils.simpleObjectMapperAllowingDuplicatedProperties; } else { Utils.simpleObjectMapper = Utils.simpleObjectMapperDisallowingDuplicatedProperties; } } /** * Joins the specified paths by appropriately padding them with '/' * * @param path1 the first path segment to join. * @param path2 the second path segment to join. * @return the concatenated path with '/' */ public static String joinPath(String path1, String path2) { path1 = trimBeginningAndEndingSlashes(path1); String result = "/" + path1 + "/"; if (!StringUtils.isEmpty(path2)) { path2 = trimBeginningAndEndingSlashes(path2); result += path2 + "/"; } return result; } /** * Trims the beginning and ending '/' from the given path * * @param path the path to trim for beginning and ending slashes * @return the path without beginning and ending '/' */ public static String trimBeginningAndEndingSlashes(String path) { if(path == null) { return null; } if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path; } public static String createQuery(Map<String, String> queryParameters) { if (queryParameters == null) return ""; StringBuilder queryString = new StringBuilder(); for (Map.Entry<String, String> nameValuePair : queryParameters.entrySet()) { String key = nameValuePair.getKey(); String value = nameValuePair.getValue(); if (key != null && !key.isEmpty()) { if (queryString.length() > 0) { queryString.append(RuntimeConstants.Separators.Query[1]); } queryString.append(key); if (value != null) { queryString.append(RuntimeConstants.Separators.Query[2]); queryString.append(value); } } } return queryString.toString(); } public static URI setQuery(String urlString, String query) { if (urlString == null) throw new IllegalStateException("urlString parameter can't be null."); query = Utils.removeLeadingQuestionMark(query); try { if (query != null && !query.isEmpty()) { return new URI(Utils.addTrailingSlash(urlString) + RuntimeConstants.Separators.Query[0] + query); } else { return new URI(Utils.addTrailingSlash(urlString)); } } catch (URISyntaxException e) { throw new IllegalStateException("Uri is invalid: ", e); } } /** * Given the full path to a resource, extract the collection path. * * @param resourceFullName the full path to the resource. * @return the path of the collection in which the resource is. */ public static String getCollectionName(String resourceFullName) { if (resourceFullName != null) { resourceFullName = Utils.trimBeginningAndEndingSlashes(resourceFullName); int slashCount = 0; for (int i = 0; i < resourceFullName.length(); i++) { if (resourceFullName.charAt(i) == '/') { slashCount++; if (slashCount == 4) { return resourceFullName.substring(0, i); } } } } return resourceFullName; } public static <T> int getCollectionSize(Collection<T> collection) { if (collection == null) { return 0; } return collection.size(); } public static boolean isCollectionChild(ResourceType type) { return type == ResourceType.Document || type == ResourceType.Attachment || type == ResourceType.Conflict || type == ResourceType.StoredProcedure || type == ResourceType.Trigger || type == ResourceType.UserDefinedFunction; } public static boolean isWriteOperation(OperationType operationType) { return operationType == OperationType.Create || operationType == OperationType.Upsert || operationType == OperationType.Delete || operationType == OperationType.Replace || operationType == OperationType.ExecuteJavaScript || operationType == OperationType.Batch; } private static String addTrailingSlash(String path) { if (path == null || path.isEmpty()) path = new String(RuntimeConstants.Separators.Url); else if (path.charAt(path.length() - 1) != RuntimeConstants.Separators.Url[0]) path = path + RuntimeConstants.Separators.Url[0]; return path; } private static String removeLeadingQuestionMark(String path) { if (path == null || path.isEmpty()) return path; if (path.charAt(0) == RuntimeConstants.Separators.Query[0]) return path.substring(1); return path; } public static boolean isValidConsistency(ConsistencyLevel backendConsistency, ConsistencyLevel desiredConsistency) { switch (backendConsistency) { case STRONG: return desiredConsistency == ConsistencyLevel.STRONG || desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case BOUNDED_STALENESS: return desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case SESSION: case EVENTUAL: case CONSISTENT_PREFIX: return desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; default: throw new IllegalArgumentException("backendConsistency"); } } public static String getUserAgent() { return getUserAgent(HttpConstants.Versions.SDK_NAME, HttpConstants.Versions.getSdkVersion()); } public static String getUserAgent(String sdkName, String sdkVersion) { String osName = System.getProperty("os.name"); if (osName == null) { osName = "Unknown"; } osName = SPACE_PATTERN.matcher(osName).replaceAll(""); return String.format("%s%s/%s %s/%s JRE/%s", UserAgentContainer.AZSDK_USERAGENT_PREFIX, sdkName, sdkVersion, osName, System.getProperty("os.version"), System.getProperty("java.version") ); } public static ObjectMapper getSimpleObjectMapper() { return Utils.simpleObjectMapper; } public static ObjectMapper getDurationEnabledObjectMapper() { return durationEnabledObjectMapper; } /** * Returns Current Time in RFC 1123 format, e.g, * Fri, 01 Dec 2017 19:22:30 GMT. * * @return an instance of STRING */ public static String nowAsRFC1123() { ZonedDateTime now = ZonedDateTime.now(GMT_ZONE_ID); return Utils.RFC_1123_DATE_TIME.format(now); } public static UUID randomUUID() { return TIME_BASED_GENERATOR.generate(); } public static String instantAsUTCRFC1123(Instant instant){ return Utils.RFC_1123_DATE_TIME.format(instant.atZone(GMT_ZONE_ID)); } public static int getValueOrDefault(Integer val, int defaultValue) { return val != null ? val : defaultValue; } public static void checkStateOrThrow(boolean value, String argumentName, String message) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, message); if (t != null) { throw t; } } public static void checkNotNullOrThrow(Object val, String argumentName, String message) throws NullPointerException { NullPointerException t = checkNotNullOrReturnException(val, argumentName, message); if (t != null) { throw t; } } public static void checkStateOrThrow(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, argumentName, messageTemplateParams); if (t != null) { throw t; } } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String message) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, message)); } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } private static NullPointerException checkNotNullOrReturnException(Object val, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (val != null) { return null; } return new NullPointerException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } @SuppressWarnings("unchecked") public static <O, I> O as(I i, Class<O> klass) { if (i == null) { return null; } if (klass.isInstance(i)) { return (O) i; } else { return null; } } @SuppressWarnings("unchecked") public static <V> List<V> immutableListOf() { return Collections.EMPTY_LIST; } public static <K, V> Map<K, V>immutableMapOf(K k1, V v1) { Map<K, V> map = new HashMap<>(); map.put(k1, v1); map = Collections.unmodifiableMap(map); return map; } public static <V> V firstOrDefault(List<V> list) { return list.size() > 0? list.get(0) : null ; } public static class ValueHolder<V> { public ValueHolder() { } public ValueHolder(V v) { this.v = v; } public V v; public static <T> ValueHolder<T> initialize(T v) { return new ValueHolder<>(v); } } public static <K, V> boolean tryGetValue(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.get(key); return holder.v != null; } public static <K, V> boolean tryRemove(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.remove(key); return holder.v != null; } public static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) { if (StringUtils.isEmpty(itemResponseBodyAsString)) { return null; } try { return getSimpleObjectMapper().readValue(itemResponseBodyAsString, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse string [%s] to POJO.", itemResponseBodyAsString), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType) { if (Utils.isEmpty(item)) { return null; } try { return getSimpleObjectMapper().readValue(item, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse byte-array %s to POJO.", Arrays.toString(item)), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType, ItemDeserializer itemDeserializer) { if (Utils.isEmpty(item)) { return null; } if (itemDeserializer == null) { return Utils.parse(item, itemClassType); } return itemDeserializer.parseFrom(itemClassType, item); } public static ByteBuffer serializeJsonToByteBuffer(ObjectMapper objectMapper, Object object) { try { ByteBufferOutputStream byteBufferOutputStream = new ByteBufferOutputStream(ONE_KB); objectMapper.writeValue(byteBufferOutputStream, object); return byteBufferOutputStream.asByteBuffer(); } catch (IOException e) { throw new IllegalArgumentException("Failed to serialize the object into json", e); } } public static boolean isEmpty(byte[] bytes) { return bytes == null || bytes.length == 0; } public static String utf8StringFromOrNull(byte[] bytes) { if (bytes == null) { return null; } return new String(bytes, StandardCharsets.UTF_8); } public static void setContinuationTokenAndMaxItemCount(CosmosPagedFluxOptions pagedFluxOptions, CosmosQueryRequestOptions cosmosQueryRequestOptions) { if (pagedFluxOptions == null) { return; } if (pagedFluxOptions.getRequestContinuation() != null) { ModelBridgeInternal.setQueryRequestOptionsContinuationToken(cosmosQueryRequestOptions, pagedFluxOptions.getRequestContinuation()); } if (pagedFluxOptions.getMaxItemCount() != null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions.getMaxItemCount()); } else { ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .applyMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions); if (pagedFluxOptions.getMaxItemCount() == null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount( cosmosQueryRequestOptions, Constants.Properties.DEFAULT_MAX_PAGE_SIZE); pagedFluxOptions.setMaxItemCount(Constants.Properties.DEFAULT_MAX_PAGE_SIZE); } } } public static CosmosChangeFeedRequestOptions getEffectiveCosmosChangeFeedRequestOptions( CosmosPagedFluxOptions pagedFluxOptions, CosmosChangeFeedRequestOptions cosmosChangeFeedRequestRequestOptions) { checkNotNull( cosmosChangeFeedRequestRequestOptions, "Argument 'cosmosChangeFeedRequestRequestOptions' must not be null"); return ModelBridgeInternal .getEffectiveChangeFeedRequestOptions( cosmosChangeFeedRequestRequestOptions, pagedFluxOptions); } static String escapeNonAscii(String partitionKeyJson) { StringBuilder sb = null; for (int i = 0; i < partitionKeyJson.length(); i++) { int val = partitionKeyJson.charAt(i); if (val > 127) { if (sb == null) { sb = new StringBuilder(partitionKeyJson.length()); sb.append(partitionKeyJson, 0, i); } sb.append("\\u").append(String.format("%04X", val)); } else { if (sb != null) { sb.append(partitionKeyJson.charAt(i)); } } } if (sb == null) { return partitionKeyJson; } else { return sb.toString(); } } public static byte[] toByteArray(ByteBuf buf) { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); return bytes; } public static String toJson(ObjectMapper mapper, ObjectNode object) { try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert JSON to STRING", e); } } public static long getMaxIntegratedCacheStalenessInMillis(DedicatedGatewayRequestOptions dedicatedGatewayRequestOptions) { Duration maxIntegratedCacheStaleness = dedicatedGatewayRequestOptions.getMaxIntegratedCacheStaleness(); if (maxIntegratedCacheStaleness.toNanos() > 0 && maxIntegratedCacheStaleness.toMillis() <= 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness granularity is milliseconds"); } if (maxIntegratedCacheStaleness.toMillis() < 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness duration cannot be negative"); } return maxIntegratedCacheStaleness.toMillis(); } }
I am curious if we have an out of the box way to compute duration here.
public void gatewayDiagnosticsOnException() throws Exception { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = null; try { createResponse = this.containerGateway.createItem(internalObjectNode); CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey")); CosmosItemResponse<InternalObjectNode> readResponse = this.containerGateway.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey("wrongPartitionKey"), InternalObjectNode.class); fail("request should fail as partition key is wrong"); } catch (CosmosException exception) { System.out.println(exception.getDiagnostics()); isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND); assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).contains("gatewayStatisticsList"); assertThat(diagnostics).contains("\"statusCode\":404"); assertThat(diagnostics).contains("\"operationType\":\"Read\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).contains("\"exceptionMessage\":\"Message: {\\\"Errors\\\":[\\\"Resource Not Found. Learn more: https:\\\\/\\\\/aka.ms\\\\/cosmosdb-tsg-not-found\\\""); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(createResponse.getDiagnostics().getContactedRegionNames()).isNotNull(); validateRegionContacted(createResponse.getDiagnostics(), this.containerGateway.asyncContainer.getDatabase().getClient()); assertThat(createResponse.getDiagnostics().getRegionsContacted()).isNotEmpty(); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); validateTransportRequestTimelineGateway(diagnostics); isValidJSON(diagnostics); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void systemDiagnosticsForSystemStateInformation() { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = this.containerGateway.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("systemInformation"); assertThat(diagnostics).contains("usedMemory"); assertThat(diagnostics).contains("availableMemory"); assertThat(diagnostics).contains("systemCpuLoad"); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnostics() throws Exception { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = containerDirect.createItem(internalObjectNode); validateDirectModeDiagnosticsOnSuccess(createResponse.getDiagnostics(), directClient, this.directClientUserAgent); try { containerDirect.createItem(internalObjectNode); fail("expected 409"); } catch (CosmosException e) { validateDirectModeDiagnosticsOnException(e, this.directClientUserAgent); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void requestSessionTokenDiagnostics() { CosmosClient testSessionTokenClient = null; try { testSessionTokenClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .consistencyLevel(ConsistencyLevel.SESSION) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer cosmosContainer = testSessionTokenClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"requestSessionToken\":null"); String sessionToken = createResponse.getSessionToken(); CosmosItemResponse<InternalObjectNode> readResponse = cosmosContainer.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey(BridgeInternal.getProperties(createResponse).getId()), InternalObjectNode.class); diagnostics = readResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"requestSessionToken\":\"%s\"", sessionToken)); CosmosBatch batch = CosmosBatch.createCosmosBatch(new PartitionKey( BridgeInternal.getProperties(createResponse).getId())); internalObjectNode = getInternalObjectNode(); batch.createItemOperation(internalObjectNode); CosmosBatchResponse batchResponse = cosmosContainer.executeCosmosBatch(batch, new CosmosBatchRequestOptions().setSessionToken(readResponse.getSessionToken())); diagnostics = batchResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"requestSessionToken\":\"%s\"", readResponse.getSessionToken())); } finally { if (testSessionTokenClient != null) { testSessionTokenClient.close(); } } } @Test(groups = {"simple"}) public void databaseAccountToClients() { CosmosClient testClient = null; try { testClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer cosmosContainer = testClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"clientEndpoints\"" + ":{\"%s\"", TestConfigurations.HOST)); int clientsIndex = diagnostics.indexOf("\"clientEndpoints\":"); String[] substrings = diagnostics.substring(clientsIndex, clientsIndex + 120) .split("}")[0].split(":"); String intString = substrings[substrings.length-1]; int intValue = Integer.parseInt(intString); CosmosClient testClient2 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); internalObjectNode = getInternalObjectNode(); createResponse = cosmosContainer.createItem(internalObjectNode); diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"clientEndpoints\"" + ":{\"%s\"", TestConfigurations.HOST)); clientsIndex = diagnostics.indexOf("\"clientEndpoints\":"); substrings = diagnostics.substring(clientsIndex, clientsIndex + 120) .split("}")[0].split(":"); intString = substrings[substrings.length-1]; assertThat(Integer.parseInt(intString)).isEqualTo(intValue+1); testClient2.close(); } finally { if (testClient != null) { testClient.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryPlanDiagnostics() throws JsonProcessingException { List<String> itemIdList = new ArrayList<>(); for(int i = 0; i< 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = containerDirect.createItem(internalObjectNode); if(i%20 == 0) { itemIdList.add(internalObjectNode.getId()); } } String queryDiagnostics = null; List<String> queryList = new ArrayList<>(); queryList.add("Select * from c"); StringBuilder queryBuilder = new StringBuilder("SELECT * from c where c.mypk in ("); for(int i = 0 ; i < itemIdList.size(); i++){ queryBuilder.append("'").append(itemIdList.get(i)).append("'"); if(i < (itemIdList.size()-1)) { queryBuilder.append(","); } else { queryBuilder.append(")"); } } queryList.add(queryBuilder.toString()); queryList.add("Select * from c where c.id = 'wrongId'"); for(String query : queryList) { int feedResponseCounter = 0; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setQueryMetricsEnabled(true); Iterator<FeedResponse<InternalObjectNode>> iterator = containerDirect.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); if (feedResponseCounter == 0) { assertThat(queryDiagnostics).contains("queryPlanDiagnosticsContext"); assertThat(queryDiagnostics).contains("startTimeUTC"); assertThat(queryDiagnostics).contains("endTimeUTC"); String requestTimeLine = OBJECT_MAPPER.writeValueAsString(feedResponse.getCosmosDiagnostics().getFeedResponseDiagnostics().getQueryPlanDiagnosticsContext().getRequestTimeline()); assertThat(requestTimeLine).contains("connectionConfigured"); assertThat(requestTimeLine).contains("requestSent"); assertThat(requestTimeLine).contains("transitTime"); assertThat(requestTimeLine).contains("received"); } else { assertThat(queryDiagnostics).contains("\"queryPlanDiagnosticsContext\":null"); } feedResponseCounter++; } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readManyDiagnostics() { String pkValue = UUID.randomUUID().toString(); PartitionKey partitionKey = new PartitionKey(pkValue); List<CosmosItemIdentity> itemIdList = new ArrayList<>(); for(int i = 0; i< 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(pkValue); CosmosItemResponse<InternalObjectNode> createResponse = containerDirect.createItem(internalObjectNode); if(i%20 == 0) { itemIdList.add(new CosmosItemIdentity(partitionKey, internalObjectNode.getId())); } } FeedResponse<InternalObjectNode> response = containerDirect.readMany(itemIdList, InternalObjectNode.class); FeedResponseDiagnostics diagnostics = response.getCosmosDiagnostics().getFeedResponseDiagnostics(); assertThat(diagnostics.getClientSideRequestStatistics().size()).isEqualTo(1); assertThat(diagnostics.getQueryMetricsMap().values().iterator().next().getRetrievedDocumentCount()).isEqualTo(itemIdList.size()); String cosmosDiagnosticsString = response.getCosmosDiagnostics().toString(); assertThat(cosmosDiagnosticsString).contains("\"userAgent\":\"" + this.directClientUserAgent + "\""); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryMetricsWithIndexMetrics() { List<String> itemIdList = new ArrayList<>(); for(int i = 0; i< 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = containerDirect.createItem(internalObjectNode); if(i%20 == 0) { itemIdList.add(internalObjectNode.getId()); } } String queryDiagnostics = null; List<String> queryList = new ArrayList<>(); StringBuilder queryBuilder = new StringBuilder("SELECT * from c where c.mypk in ("); for(int i = 0 ; i < itemIdList.size(); i++){ queryBuilder.append("'").append(itemIdList.get(i)).append("'"); if(i < (itemIdList.size()-1)) { queryBuilder.append(","); } else { queryBuilder.append(")"); } } queryList.add(queryBuilder.toString()); for (String query : queryList) { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setQueryMetricsEnabled(true); options.setIndexMetricsEnabled(true); Iterator<FeedResponse<InternalObjectNode>> iterator = containerDirect.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); logger.info("This is query diagnostics {}", queryDiagnostics); if (feedResponse.getResponseHeaders().containsKey(HttpConstants.HttpHeaders.INDEX_UTILIZATION)) { assertThat(feedResponse.getResponseHeaders().get(HttpConstants.HttpHeaders.INDEX_UTILIZATION)).isNotNull(); assertThat(createFromJSONString(Utils.decodeBase64String(feedResponse.getResponseHeaders().get(HttpConstants.HttpHeaders.INDEX_UTILIZATION))).getUtilizedSingleIndexes()).isNotNull(); } } } } @Test(groups = {"simple"}, dataProvider = "query", timeOut = TIMEOUT) public void queryMetrics(String query, Boolean qmEnabled) { CosmosContainer directContainer = this.directClient.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()) .getContainer(this.cosmosAsyncContainer.getId()); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); if (qmEnabled != null) { options.setQueryMetricsEnabled(qmEnabled); } boolean qroupByFirstResponse = true; Iterator<FeedResponse<InternalObjectNode>> iterator = directContainer.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); assertThat(iterator.hasNext()).isTrue(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); assertThat(feedResponse.getResults().size()).isEqualTo(0); if (!query.contains("group by") || qroupByFirstResponse) { validateQueryDiagnostics(queryDiagnostics, qmEnabled, true); validateDirectModeQueryDiagnostics(queryDiagnostics, this.directClientUserAgent); if (query.contains("group by")) { qroupByFirstResponse = false; } } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryDiagnosticsOnOrderBy() { String containerId = "testcontainer"; cosmosAsyncDatabase.createContainer(containerId, "/mypk", ThroughputProperties.createManualThroughput(40000)).block(); CosmosAsyncContainer testcontainer = cosmosAsyncDatabase.getContainer(containerId); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setConsistencyLevel(ConsistencyLevel.EVENTUAL); testcontainer.createItem(getInternalObjectNode()).block(); options.setMaxDegreeOfParallelism(-1); String query = "SELECT * from c ORDER BY c._ts DESC"; CosmosPagedFlux<InternalObjectNode> cosmosPagedFlux = testcontainer.queryItems(query, options, InternalObjectNode.class); Set<String> partitionKeyRangeIds = new HashSet<>(); Set<String> pkRids = new HashSet<>(); cosmosPagedFlux.byPage().flatMap(feedResponse -> { String cosmosDiagnosticsString = feedResponse.getCosmosDiagnostics().toString(); Pattern pattern = Pattern.compile("(\"partitionKeyRangeId\":\")(\\d)"); Matcher matcher = pattern.matcher(cosmosDiagnosticsString); while (matcher.find()) { String group = matcher.group(2); partitionKeyRangeIds.add(group); } pattern = Pattern.compile("(pkrId:)(\\d)"); matcher = pattern.matcher(cosmosDiagnosticsString); while (matcher.find()) { String group = matcher.group(2); pkRids.add(group); } return Flux.just(feedResponse); }).blockLast(); assertThat(pkRids).isNotEmpty(); assertThat(pkRids).isEqualTo(partitionKeyRangeIds); deleteCollection(testcontainer); } @Test(groups = {"simple"}, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) public void directDiagnosticsOnCancelledOperation(OperationType operationType) { CosmosAsyncClient client = null; FaultInjectionRule faultInjectionRule = null; try { client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(TestConfigurations.HOST) .endToEndOperationLatencyPolicyConfig( new CosmosEndToEndOperationLatencyPolicyConfigBuilder(Duration.ofSeconds(1)).build() ).buildAsyncClient(); CosmosAsyncContainer container = client.getDatabase(containerDirect.asyncContainer.getDatabase().getId()).getContainer(containerDirect.getId()); TestItem testItem = TestItem.createNewItem(); container.createItem(testItem).block(); faultInjectionRule = new FaultInjectionRuleBuilder("responseDelay") .condition(new FaultInjectionConditionBuilder().build()) .result( FaultInjectionResultBuilders.getResultBuilder(FaultInjectionServerErrorType.RESPONSE_DELAY) .delay(Duration.ofSeconds(2)) .build() ) .build(); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(faultInjectionRule)).block(); this.performDocumentOperation(container, operationType, testItem); fail("expected OperationCancelledException"); } catch (CosmosException e) { assertThat(e).isInstanceOf(OperationCancelledException.class); String cosmosDiagnosticsString = e.getDiagnostics().toString(); assertThat(cosmosDiagnosticsString).contains("\"statusCode\":408"); assertThat(cosmosDiagnosticsString).contains("\"subStatusCode\":20008"); } finally { if (faultInjectionRule != null) { faultInjectionRule.disable(); } safeClose(client); } } @Test(groups = {"simple"}, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) public void directDiagnostics_WithFaultInjection(OperationType operationType) { CosmosAsyncClient client = null; FaultInjectionRule faultInjectionRule = null; try { client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(TestConfigurations.HOST) .buildAsyncClient(); CosmosAsyncContainer container = client.getDatabase(containerDirect.asyncContainer.getDatabase().getId()).getContainer(containerDirect.getId()); TestItem testItem = TestItem.createNewItem(); container.createItem(testItem).block(); faultInjectionRule = new FaultInjectionRuleBuilder("serverResponseError") .condition(new FaultInjectionConditionBuilder().build()) .result( FaultInjectionResultBuilders.getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .build(); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(faultInjectionRule)).block(); CosmosDiagnostics cosmosDiagnostics = this.performDocumentOperation(container, operationType, testItem); assertThat(cosmosDiagnostics).isNotNull(); String diagnosticsString = cosmosDiagnostics.toString(); assertThat(diagnosticsString).contains("\"statusCode\":410"); assertThat(diagnosticsString).contains("\"subStatusCode\":21005"); assertThat(diagnosticsString).doesNotContain("\"statusCode\":408"); assertThat(diagnosticsString).doesNotContain("\"subStatusCode\":20008"); } catch (CosmosException e) { fail("Request should succeeded but failed with " + e.getMessage()); } finally { if (faultInjectionRule != null) { faultInjectionRule.disable(); } safeClose(client); } } private void validateDirectModeDiagnosticsOnSuccess( CosmosDiagnostics cosmosDiagnostics, CosmosClient testDirectClient, String userAgent) throws Exception { String diagnostics = cosmosDiagnostics.toString(); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("supplementalResponseStatisticsList"); assertThat(diagnostics).contains("gatewayStatisticsList"); assertThat(diagnostics).contains("addressResolutionStatistics"); assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\""); assertThat(diagnostics).contains("\"metaDataName\":\"PARTITION_KEY_RANGE_LOOK_UP\""); assertThat(diagnostics).contains("\"metaDataName\":\"SERVER_ADDRESS_LOOKUP\""); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + userAgent + "\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"backendLatencyInMs\""); assertThat(diagnostics).contains("\"retryAfterInMs\""); assertThat(diagnostics).contains("\"channelStatistics\""); assertThat(cosmosDiagnostics.getContactedRegionNames()).isNotEmpty(); assertThat(cosmosDiagnostics.getDuration()).isNotNull(); validateTransportRequestTimelineDirect(diagnostics); validateRegionContacted(cosmosDiagnostics, testDirectClient.asyncClient()); validateChannelStatistics(cosmosDiagnostics); isValidJSON(diagnostics); } private void validateDirectModeDiagnosticsOnException(CosmosException cosmosException, String userAgent) { CosmosDiagnostics cosmosDiagnostics = cosmosException.getDiagnostics(); String diagnosticsString = cosmosDiagnostics.toString(); assertThat(diagnosticsString).contains("\"backendLatencyInMs\""); assertThat(diagnosticsString).contains("\"userAgent\":\"" + userAgent + "\""); assertThat(diagnosticsString).contains("\"retryAfterInMs\""); assertThat(diagnosticsString).contains("\"exceptionMessage\":\"[\\\"Resource with specified id or name already exists.\\\"]\""); assertThat(diagnosticsString).contains("\"exceptionResponseHeaders\""); assertThat(diagnosticsString).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); validateTransportRequestTimelineDirect(diagnosticsString); validateChannelStatistics(cosmosDiagnostics); if (!(cosmosException instanceof OperationCancelledException)) { assertThat(diagnosticsString).doesNotContain("\"statusCode\":408"); assertThat(diagnosticsString).doesNotContain("\"subStatusCode\":20008"); } } private void validateDirectModeQueryDiagnostics(String diagnostics, String userAgent) { assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("supplementalResponseStatisticsList"); assertThat(diagnostics).contains("responseStatisticsList"); assertThat(diagnostics).contains("gatewayStatisticsList"); assertThat(diagnostics).contains("addressResolutionStatistics"); assertThat(diagnostics).contains("\"userAgent\":\"" + userAgent + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); } private void validateGatewayModeQueryDiagnostics(String diagnostics, String userAgent) { assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).contains(("gatewayStatisticsList")); assertThat(diagnostics).contains("\"operationType\":\"Query\""); assertThat(diagnostics).contains("\"userAgent\":\"" + userAgent + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"regionsContacted\""); } @Test(groups = {"simple"}, dataProvider = "query", timeOut = TIMEOUT*2) public void queryDiagnosticsGatewayMode(String query, Boolean qmEnabled) { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); List<String> itemIdList = new ArrayList<>(); for (int i = 0; i < 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); containerGateway.createItem(internalObjectNode); if (i % 20 == 0) { itemIdList.add(internalObjectNode.getId()); } } boolean qroupByFirstResponse = true; if (qmEnabled != null) { options.setQueryMetricsEnabled(qmEnabled); } Iterator<FeedResponse<InternalObjectNode>> iterator = containerGateway .queryItems(query, options, InternalObjectNode.class) .iterableByPage() .iterator(); assertThat(iterator.hasNext()).isTrue(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); assertThat(feedResponse.getResults().size()).isEqualTo(0); if (!query.contains("group by") || qroupByFirstResponse) { validateQueryDiagnostics(queryDiagnostics, qmEnabled, true); validateGatewayModeQueryDiagnostics(queryDiagnostics, this.gatewayClientUserAgent); if (query.contains("group by")) { qroupByFirstResponse = false; } } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryMetricsWithADifferentLocale() { Locale.setDefault(Locale.GERMAN); String query = "select * from root where root.id= \"someid\""; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); Iterator<FeedResponse<InternalObjectNode>> iterator = this.containerGateway.queryItems(query, options, InternalObjectNode.class) .iterableByPage().iterator(); double requestCharge = 0; while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); requestCharge += feedResponse.getRequestCharge(); } assertThat(requestCharge).isGreaterThan(0); Locale.setDefault(Locale.ROOT); } private static void validateQueryDiagnostics( String queryDiagnostics, Boolean qmEnabled, boolean expectQueryPlanDiagnostics) { if (qmEnabled == null || qmEnabled) { assertThat(queryDiagnostics).contains("retrievedDocumentCount"); assertThat(queryDiagnostics).contains("queryPreparationTimes"); assertThat(queryDiagnostics).contains("runtimeExecutionTimes"); assertThat(queryDiagnostics).contains("fetchExecutionRanges"); } else { assertThat(queryDiagnostics).doesNotContain("retrievedDocumentCount"); assertThat(queryDiagnostics).doesNotContain("queryPreparationTimes"); assertThat(queryDiagnostics).doesNotContain("runtimeExecutionTimes"); assertThat(queryDiagnostics).doesNotContain("fetchExecutionRanges"); } if (expectQueryPlanDiagnostics) { assertThat(queryDiagnostics).contains("queryPlanDiagnosticsContext"); assertThat(queryDiagnostics).contains("startTimeUTC"); assertThat(queryDiagnostics).contains("endTimeUTC"); } else { assertThat(queryDiagnostics).contains("\"queryPlanDiagnosticsContext\":null"); } } @Test(groups = {"simple"}, dataProvider = "readAllItemsOfLogicalPartition", timeOut = TIMEOUT) public void queryMetricsForReadAllItemsOfLogicalPartition(Integer expectedItemCount, Boolean qmEnabled) { String pkValue = UUID.randomUUID().toString(); for (int i = 0; i < expectedItemCount; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(pkValue); CosmosItemResponse<InternalObjectNode> createResponse = containerGateway.createItem(internalObjectNode); } CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); if (qmEnabled != null) { options = options.setQueryMetricsEnabled(qmEnabled); } ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(options, 5); Iterator<FeedResponse<InternalObjectNode>> iterator = this.containerGateway .readAllItems( new PartitionKey(pkValue), options, InternalObjectNode.class) .iterableByPage().iterator(); assertThat(iterator.hasNext()).isTrue(); int actualItemCount = 0; while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); actualItemCount += feedResponse.getResults().size(); validateQueryDiagnostics(queryDiagnostics, qmEnabled, false); } assertThat(actualItemCount).isEqualTo(expectedItemCount); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnosticsOnException() throws Exception { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = null; try { createResponse = containerDirect.createItem(internalObjectNode); CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey")); CosmosItemResponse<InternalObjectNode> readResponse = containerDirect.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey("wrongPartitionKey"), InternalObjectNode.class); fail("request should fail as partition key is wrong"); } catch (CosmosException exception) { isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.directClientUserAgent + "\""); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(exception.getDiagnostics().getContactedRegionNames()).isNotEmpty(); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); assertThat(diagnostics).contains("\"backendLatencyInMs\""); assertThat(diagnostics).contains("\"retryAfterInMs\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"exceptionMessage\":\"[\\\"Resource Not Found."); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\":null"); isValidJSON(diagnostics); validateTransportRequestTimelineDirect(diagnostics); validateRegionContacted(createResponse.getDiagnostics(), directClient.asyncClient()); ObjectNode diagnosticsNode = (ObjectNode) OBJECT_MAPPER.readTree(diagnostics); JsonNode responseStatisticsList = diagnosticsNode.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); assertThat(responseStatisticsList.size()).isGreaterThan(0); JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); assertThat(storeResult).isNotNull(); JsonNode replicaStatusList = storeResult.get("replicaStatusList"); assertThat(replicaStatusList.isArray()).isTrue(); assertThat(replicaStatusList.size()).isGreaterThan(0); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnosticsOnMetadataException() { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosClient client = null; try { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer container = client.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); HttpClient mockHttpClient = Mockito.mock(HttpClient.class); Mockito.when(mockHttpClient.send(Mockito.any(HttpRequest.class), Mockito.any(Duration.class))) .thenReturn(Mono.error(new CosmosException(400, "TestBadRequest"))); RxStoreModel rxGatewayStoreModel = rxGatewayStoreModel = ReflectionUtils.getGatewayProxy((RxDocumentClientImpl) client.asyncClient().getDocClientWrapper()); ReflectionUtils.setGatewayHttpClient(rxGatewayStoreModel, mockHttpClient); container.createItem(internalObjectNode); fail("request should fail as bad request"); } catch (CosmosException exception) { isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.BADREQUEST); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("\"exceptionMessage\":\"TestBadRequest\""); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(diagnostics).contains("\"resourceType\":\"DocumentCollection\""); assertThat(exception.getDiagnostics().getContactedRegionNames()).isNotEmpty(); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); isValidJSON(diagnostics); } finally { if (client != null) { client.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void supplementalResponseStatisticsList() throws Exception { ClientSideRequestStatistics clientSideRequestStatistics = new ClientSideRequestStatistics(mockDiagnosticsClientContext()); for (int i = 0; i < 15; i++) { RxDocumentServiceRequest rxDocumentServiceRequest = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Head, ResourceType.Document); clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, null, null); } List<ClientSideRequestStatistics.StoreResponseStatistics> storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); ObjectMapper objectMapper = new ObjectMapper(); String diagnostics = objectMapper.writeValueAsString(clientSideRequestStatistics); JsonNode jsonNode = objectMapper.readTree(diagnostics); ArrayNode supplementalResponseStatisticsListNode = (ArrayNode) jsonNode.get("supplementalResponseStatisticsList"); assertThat(storeResponseStatistics.size()).isEqualTo(15); assertThat(supplementalResponseStatisticsListNode.size()).isEqualTo(10); clearStoreResponseStatistics(clientSideRequestStatistics); storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); assertThat(storeResponseStatistics.size()).isEqualTo(0); for (int i = 0; i < 7; i++) { RxDocumentServiceRequest rxDocumentServiceRequest = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Head, ResourceType.Document); clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, null, null); } storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); objectMapper = new ObjectMapper(); diagnostics = objectMapper.writeValueAsString(clientSideRequestStatistics); jsonNode = objectMapper.readTree(diagnostics); supplementalResponseStatisticsListNode = (ArrayNode) jsonNode.get("supplementalResponseStatisticsList"); assertThat(storeResponseStatistics.size()).isEqualTo(7); assertThat(supplementalResponseStatisticsListNode.size()).isEqualTo(7); for(JsonNode node : supplementalResponseStatisticsListNode) { assertThat(node.get("storeResult").asText()).isNotNull(); String requestResponseTimeUTC = node.get("requestResponseTimeUTC").asText(); Instant instant = Instant.from(RESPONSE_TIME_FORMATTER.parse(requestResponseTimeUTC)); assertThat(Instant.now().toEpochMilli() - instant.toEpochMilli()).isLessThan(5000); assertThat(node.get("requestResponseTimeUTC")).isNotNull(); assertThat(node.get("requestOperationType")).isNotNull(); assertThat(node.get("requestSessionToken")).isNotNull(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void serializationOnVariousScenarios() { CosmosDatabaseResponse cosmosDatabase = gatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).read(); String diagnostics = cosmosDatabase.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"DATABASE_DESERIALIZATION\""); CosmosContainerResponse containerResponse = this.containerGateway.read(); diagnostics = containerResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"CONTAINER_DESERIALIZATION\""); TestItem testItem = new TestItem(); testItem.id = "TestId"; testItem.mypk = "TestPk"; CosmosItemResponse<TestItem> itemResponse = this.containerGateway.createItem(testItem); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); testItem.id = "TestId2"; testItem.mypk = "TestPk"; itemResponse = this.containerGateway.createItem(testItem, new PartitionKey("TestPk"), null); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).doesNotContain("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).doesNotContain("\"serializationType\":\"ITEM_DESERIALIZATION\""); TestItem readTestItem = itemResponse.getItem(); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"ITEM_DESERIALIZATION\""); CosmosItemResponse<InternalObjectNode> readItemResponse = this.containerGateway.readItem(testItem.id, new PartitionKey(testItem.mypk), null, InternalObjectNode.class); InternalObjectNode properties = readItemResponse.getItem(); diagnostics = readItemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"ITEM_DESERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void rntbdRequestResponseLengthStatistics() throws Exception { TestItem testItem = new TestItem(); testItem.id = UUID.randomUUID().toString(); testItem.mypk = UUID.randomUUID().toString(); int testItemLength = OBJECT_MAPPER.writeValueAsBytes(testItem).length; CosmosContainer container = directClient.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()).getContainer(this.cosmosAsyncContainer.getId()); CosmosItemResponse<TestItem> createItemResponse = container.createItem(testItem); validate(createItemResponse.getDiagnostics(), testItemLength, ModelBridgeInternal.getPayloadLength(createItemResponse)); try { container.createItem(testItem); fail("expected to fail due to 409"); } catch (CosmosException e) { logger.info("Diagnostics are : {}", e.getDiagnostics()); String diagnostics = e.getDiagnostics().toString(); assertThat(diagnostics).contains("\"exceptionMessage\":\"[\\\"Resource with specified id or name already exists.\\\"]\""); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); validate(e.getDiagnostics(), testItemLength, 0); } CosmosItemResponse<TestItem> readItemResponse = container.readItem(testItem.id, new PartitionKey(testItem.mypk), TestItem.class); validate(readItemResponse.getDiagnostics(), 0, ModelBridgeInternal.getPayloadLength(readItemResponse)); CosmosItemResponse<Object> deleteItemResponse = container.deleteItem(testItem, null); validate(deleteItemResponse.getDiagnostics(), 0, 0); } @Test(groups = {"simple"}, dataProvider = "connectionStateListenerArgProvider", timeOut = TIMEOUT) public void rntbdStatistics(boolean connectionStateListenerEnabled) throws Exception { Instant beforeClientInitialization = Instant.now(); CosmosClient client1 = null; try { DirectConnectionConfig connectionConfig = DirectConnectionConfig.getDefaultConfig(); connectionConfig.setConnectionEndpointRediscoveryEnabled(connectionStateListenerEnabled); client1 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(connectionConfig) .buildClient(); TestItem testItem = new TestItem(); testItem.id = UUID.randomUUID().toString(); testItem.mypk = UUID.randomUUID().toString(); int testItemLength = OBJECT_MAPPER.writeValueAsBytes(testItem).length; CosmosContainer container = client1.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()).getContainer(this.cosmosAsyncContainer.getId()); Thread.sleep(1000); Instant beforeInitializingRntbdServiceEndpoint = Instant.now(); CosmosItemResponse<TestItem> operation1Response = container.upsertItem(testItem); Instant afterInitializingRntbdServiceEndpoint = Instant.now(); Thread.sleep(1000); Instant beforeOperation2 = Instant.now(); CosmosItemResponse<TestItem> operation2Response = container.upsertItem(testItem); Instant afterOperation2 = Instant.now(); Thread.sleep(1000); Instant beforeOperation3 = Instant.now(); CosmosItemResponse<TestItem> operation3Response = container.upsertItem(testItem); Instant afterOperation3 = Instant.now(); validateRntbdStatistics(operation3Response.getDiagnostics(), beforeClientInitialization, beforeInitializingRntbdServiceEndpoint, afterInitializingRntbdServiceEndpoint, beforeOperation2, afterOperation2, beforeOperation3, afterOperation3, connectionStateListenerEnabled); CosmosItemResponse<TestItem> readItemResponse = container.readItem(testItem.id, new PartitionKey(testItem.mypk), TestItem.class); validate(readItemResponse.getDiagnostics(), 0, ModelBridgeInternal.getPayloadLength(readItemResponse)); CosmosItemResponse<Object> deleteItemResponse = container.deleteItem(testItem, null); validate(deleteItemResponse.getDiagnostics(), 0, 0); } finally { LifeCycleUtils.closeQuietly(client1); } } private void validateRntbdStatistics(CosmosDiagnostics cosmosDiagnostics, Instant clientInitializationTime, Instant beforeInitializingRntbdServiceEndpoint, Instant afterInitializingRntbdServiceEndpoint, Instant beforeOperation2, Instant afterOperation2, Instant beforeOperation3, Instant afterOperation3, boolean connectionStateListenerEnabled) throws Exception { ObjectNode diagnostics = (ObjectNode) OBJECT_MAPPER.readTree(cosmosDiagnostics.toString()); JsonNode responseStatisticsList = diagnostics.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); assertThat(responseStatisticsList.size()).isGreaterThan(0); JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); assertThat(storeResult).isNotNull(); JsonNode replicaStatusList = storeResult.get("replicaStatusList"); assertThat(replicaStatusList.isArray()).isTrue(); assertThat(replicaStatusList.size()).isGreaterThan(0); JsonNode serviceEndpointStatistics = storeResult.get("serviceEndpointStatistics"); assertThat(serviceEndpointStatistics).isNotNull(); assertThat(serviceEndpointStatistics.get("availableChannels").asInt(-1)).isGreaterThan(0); assertThat(serviceEndpointStatistics.get("acquiredChannels").asInt(-1)).isEqualTo(0); assertThat(serviceEndpointStatistics.get("inflightRequests").asInt(-1)).isEqualTo(1); assertThat(serviceEndpointStatistics.get("isClosed").asBoolean()).isEqualTo(false); JsonNode channelStatistics = storeResult.get("channelStatistics"); assertThat(channelStatistics).isNotNull(); assertThat(channelStatistics.get("channelId").asText()).isNotEmpty(); assertThat(channelStatistics.get("channelTaskQueueSize").asInt(-1)).isGreaterThanOrEqualTo(0); assertThat(channelStatistics.get("pendingRequestsCount").asInt(-1)).isGreaterThanOrEqualTo(0); assertThat(channelStatistics.get("lastReadTime").asText()).isNotEmpty(); assertThat(channelStatistics.get("waitForConnectionInit").asText()).isNotEmpty(); JsonNode connectionStateListenerMetrics = serviceEndpointStatistics.get("cerMetrics"); if (connectionStateListenerEnabled) { assertThat(connectionStateListenerMetrics).isNotNull(); assertThat(connectionStateListenerMetrics.get("lastCallTimestamp")).isNull(); assertThat(connectionStateListenerMetrics.get("lastActionableContext")).isNull(); } else { assertThat(connectionStateListenerMetrics).isNull(); } Instant beforeInitializationThreshold = beforeInitializingRntbdServiceEndpoint.minusMillis(1); assertThat(Instant.parse(serviceEndpointStatistics.get("createdTime").asText())) .isAfterOrEqualTo(beforeInitializationThreshold); Instant afterInitializationThreshold = afterInitializingRntbdServiceEndpoint.plusMillis(2); assertThat(Instant.parse(serviceEndpointStatistics.get("createdTime").asText())) .isBeforeOrEqualTo(afterInitializationThreshold); Instant afterOperation2Threshold = afterOperation2.plusMillis(2); Instant beforeOperation2Threshold = beforeOperation2.minusMillis(2); assertThat(Instant.parse(serviceEndpointStatistics.get("lastRequestTime").asText())) .isAfterOrEqualTo(beforeOperation2Threshold.toString()) .isBeforeOrEqualTo(afterOperation2Threshold.toString()); assertThat(Instant.parse(serviceEndpointStatistics.get("lastSuccessfulRequestTime").asText())) .isAfterOrEqualTo(beforeOperation2Threshold.toString()) .isBeforeOrEqualTo(afterOperation2Threshold.toString()); } private void validate(CosmosDiagnostics cosmosDiagnostics, int expectedRequestPayloadSize, int expectedResponsePayloadSize) throws Exception { ObjectNode diagnostics = (ObjectNode) OBJECT_MAPPER.readTree(cosmosDiagnostics.toString()); JsonNode responseStatisticsList = diagnostics.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); assertThat(responseStatisticsList.size()).isGreaterThan(0); JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); boolean hasPayload = storeResult.get("exceptionMessage") == null; assertThat(storeResult).isNotNull(); assertThat(storeResult.get("rntbdRequestLengthInBytes").asInt(-1)).isGreaterThan(expectedRequestPayloadSize); assertThat(storeResult.get("rntbdRequestLengthInBytes").asInt(-1)).isGreaterThan(expectedRequestPayloadSize); assertThat(storeResult.get("requestPayloadLengthInBytes").asInt(-1)).isEqualTo(expectedRequestPayloadSize); if (hasPayload) { assertThat(storeResult.get("responsePayloadLengthInBytes").asInt(-1)).isEqualTo(expectedResponsePayloadSize); } assertThat(storeResult.get("rntbdResponseLengthInBytes").asInt(-1)).isGreaterThan(expectedResponsePayloadSize); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void addressResolutionStatistics() { CosmosClient client1 = null; CosmosClient client2 = null; String databaseId = DatabaseForTest.generateId(); String containerId = UUID.randomUUID().toString(); CosmosDatabase cosmosDatabase = null; CosmosContainer cosmosContainer = null; try { client1 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); client1.createDatabase(databaseId); cosmosDatabase = client1.getDatabase(databaseId); cosmosDatabase.createContainer(containerId, "/mypk"); InternalObjectNode internalObjectNode = getInternalObjectNode(); cosmosContainer = cosmosDatabase.getContainer(containerId); CosmosItemResponse<InternalObjectNode> writeResourceResponse = cosmosContainer.createItem(internalObjectNode); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("addressResolutionStatistics"); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("\"inflightRequest\":false"); assertThat(writeResourceResponse.getDiagnostics().toString()).doesNotContain("endTime=\"null\""); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("\"exceptionMessage\":null"); client2 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); cosmosDatabase = client2.getDatabase(databaseId); cosmosContainer = cosmosDatabase.getContainer(containerId); AsyncDocumentClient asyncDocumentClient = client2.asyncClient().getContextClient(); GlobalAddressResolver addressResolver = (GlobalAddressResolver) FieldUtils.readField(asyncDocumentClient, "addressResolver", true); @SuppressWarnings("rawtypes") Map addressCacheByEndpoint = (Map) FieldUtils.readField(addressResolver, "addressCacheByEndpoint", true); Object endpointCache = addressCacheByEndpoint.values().toArray()[0]; GatewayAddressCache addressCache = (GatewayAddressCache) FieldUtils.readField(endpointCache, "addressCache", true); HttpClient httpClient = httpClient(true); FieldUtils.writeField(addressCache, "httpClient", httpClient, true); new Thread(() -> { try { Thread.sleep(5000); HttpClient httpClient1 = httpClient(false); FieldUtils.writeField(addressCache, "httpClient", httpClient1, true); } catch (Exception e) { fail(e.getMessage()); } }).start(); PartitionKey partitionKey = new PartitionKey(internalObjectNode.get("mypk")); CosmosItemResponse<InternalObjectNode> readResourceResponse = cosmosContainer.readItem(internalObjectNode.getId(), partitionKey, new CosmosItemRequestOptions(), InternalObjectNode.class); assertThat(readResourceResponse.getDiagnostics().toString()).contains("addressResolutionStatistics"); assertThat(readResourceResponse.getDiagnostics().toString()).contains("\"inflightRequest\":false"); assertThat(readResourceResponse.getDiagnostics().toString()).doesNotContain("endTime=\"null\""); assertThat(readResourceResponse.getDiagnostics().toString()).contains("\"exceptionMessage\":\"io.netty" + ".channel.AbstractChannel$AnnotatedConnectException: Connection refused"); } catch (Exception ex) { logger.error("Error in test addressResolutionStatistics", ex); fail("This test should not throw exception " + ex); } finally { safeDeleteSyncDatabase(cosmosDatabase); if (client1 != null) { client1.close(); } if (client2 != null) { client2.close(); } } } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void responseStatisticRequestStartTimeUTCForDirectCall() { CosmosAsyncClient client = null; String databaseId = DatabaseForTest.generateId(); FaultInjectionRule faultInjectionRule = null; try { client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(TestConfigurations.HOST) .endToEndOperationLatencyPolicyConfig( new CosmosEndToEndOperationLatencyPolicyConfigBuilder(Duration.ofSeconds(2)).build() ).buildAsyncClient(); createDatabase(client, databaseId); CosmosAsyncContainer container = createCollection(client, databaseId, getCollectionDefinition()); TestItem testItem = TestItem.createNewItem(); container.createItem(testItem).block(); faultInjectionRule = new FaultInjectionRuleBuilder("PARTITION_IS_MIGRATING") .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.CREATE_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.PARTITION_IS_MIGRATING) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(faultInjectionRule)).block(); CosmosDiagnostics cosmosDiagnostics = null; try { cosmosDiagnostics = container.createItem(TestItem.createNewItem()) .block() .getDiagnostics(); } catch (Exception exception) { fail("Request should succeeded, but failed with " + exception); } List<ClientSideRequestStatistics> clientSideRequestStatistics = (List<ClientSideRequestStatistics>) cosmosDiagnostics.getClientSideRequestStatistics(); List<ClientSideRequestStatistics.StoreResponseStatistics> responseStatistic = clientSideRequestStatistics.get(0).getResponseStatisticsList(); assert responseStatistic.size() == 2; Instant firstRequestStartTime = responseStatistic.get(0).getRequestStartTimeUTC(); Instant secondRequestStartTime = responseStatistic.get(1).getRequestStartTimeUTC(); assert firstRequestStartTime != null && secondRequestStartTime != null; assert firstRequestStartTime != secondRequestStartTime; assert firstRequestStartTime.compareTo(secondRequestStartTime) < 0; } finally { if (faultInjectionRule != null) { faultInjectionRule.disable(); } safeClose(client); } } private InternalObjectNode getInternalObjectNode() { InternalObjectNode internalObjectNode = new InternalObjectNode(); String uuid = UUID.randomUUID().toString(); internalObjectNode.setId(uuid); BridgeInternal.setProperty(internalObjectNode, "mypk", uuid); return internalObjectNode; } private InternalObjectNode getInternalObjectNode(String pkValue) { InternalObjectNode internalObjectNode = new InternalObjectNode(); String uuid = UUID.randomUUID().toString(); internalObjectNode.setId(uuid); BridgeInternal.setProperty(internalObjectNode, "mypk", pkValue); return internalObjectNode; } private List<ClientSideRequestStatistics.StoreResponseStatistics> getStoreResponseStatistics(ClientSideRequestStatistics requestStatistics) throws Exception { Field storeResponseStatisticsField = ClientSideRequestStatistics.class.getDeclaredField("supplementalResponseStatisticsList"); storeResponseStatisticsField.setAccessible(true); @SuppressWarnings({"unchecked"}) List<ClientSideRequestStatistics.StoreResponseStatistics> list = (List<ClientSideRequestStatistics.StoreResponseStatistics>) storeResponseStatisticsField.get(requestStatistics); return list; } private void clearStoreResponseStatistics(ClientSideRequestStatistics requestStatistics) throws Exception { Field storeResponseStatisticsField = ClientSideRequestStatistics.class.getDeclaredField("supplementalResponseStatisticsList"); storeResponseStatisticsField.setAccessible(true); storeResponseStatisticsField.set(requestStatistics, new ArrayList<ClientSideRequestStatistics.StoreResponseStatistics>()); } private void validateTransportRequestTimelineGateway(String diagnostics) { assertThat(diagnostics).contains("\"eventName\":\"connectionConfigured\""); assertThat(diagnostics).contains("\"eventName\":\"requestSent\""); assertThat(diagnostics).contains("\"eventName\":\"transitTime\""); assertThat(diagnostics).contains("\"eventName\":\"received\""); } private void validateTransportRequestTimelineDirect(String diagnostics) { assertThat(diagnostics).contains("\"eventName\":\"created\""); assertThat(diagnostics).contains("\"eventName\":\"queued\""); assertThat(diagnostics).contains("\"eventName\":\"channelAcquisitionStarted\""); assertThat(diagnostics).contains("\"eventName\":\"pipelined\""); assertThat(diagnostics).contains("\"eventName\":\"transitTime\""); assertThat(diagnostics).contains("\"eventName\":\"decodeTime"); assertThat(diagnostics).contains("\"eventName\":\"received\""); assertThat(diagnostics).contains("\"eventName\":\"completed\""); assertThat(diagnostics).contains("\"startTimeUTC\""); assertThat(diagnostics).contains("\"durationInMilliSecs\""); } public void isValidJSON(final String json) { try { final JsonParser parser = new JsonFactory().createParser(json); while (parser.nextToken() != null) { } } catch (IOException ex) { fail("Diagnostic string is not in json format ", ex); } } private HttpClient httpClient(boolean fakeProxy) { HttpClientConfig httpClientConfig; if(fakeProxy) { httpClientConfig = new HttpClientConfig(new Configs()) .withProxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 8888))); } else { httpClientConfig = new HttpClientConfig(new Configs()); } return HttpClient.createFixed(httpClientConfig); } private IndexUtilizationInfo createFromJSONString(String jsonString) { ObjectMapper indexUtilizationInfoObjectMapper = new ObjectMapper(); IndexUtilizationInfo indexUtilizationInfo = null; try { indexUtilizationInfo = indexUtilizationInfoObjectMapper.readValue(jsonString, IndexUtilizationInfo.class); } catch (JsonProcessingException e) { logger.error("Json not correctly formed ", e); } return indexUtilizationInfo; } private void validateRegionContacted(CosmosDiagnostics cosmosDiagnostics, CosmosAsyncClient cosmosAsyncClient) throws Exception { RxDocumentClientImpl rxDocumentClient = (RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(cosmosAsyncClient); GlobalEndpointManager globalEndpointManager = ReflectionUtils.getGlobalEndpointManager(rxDocumentClient); LocationCache locationCache = ReflectionUtils.getLocationCache(globalEndpointManager); Field locationInfoField = LocationCache.class.getDeclaredField("locationInfo"); locationInfoField.setAccessible(true); Object locationInfo = locationInfoField.get(locationCache); Class<?> DatabaseAccountLocationsInfoClass = Class.forName("com.azure.cosmos.implementation.routing" + ".LocationCache$DatabaseAccountLocationsInfo"); Field availableWriteEndpointByLocation = DatabaseAccountLocationsInfoClass.getDeclaredField( "availableWriteEndpointByLocation"); availableWriteEndpointByLocation.setAccessible(true); @SuppressWarnings("unchecked") Map<String, URI> map = (Map<String, URI>) availableWriteEndpointByLocation.get(locationInfo); String regionName = map.keySet().iterator().next(); assertThat(cosmosDiagnostics.getContactedRegionNames().size()).isEqualTo(1); assertThat(cosmosDiagnostics.getContactedRegionNames().iterator().next()).isEqualTo(regionName.toLowerCase()); } private void validateChannelStatistics(CosmosDiagnostics cosmosDiagnostics) { for (ClientSideRequestStatistics clientSideRequestStatistics : cosmosDiagnostics.getClientSideRequestStatistics()) { for (ClientSideRequestStatistics.StoreResponseStatistics storeResponseStatistics : clientSideRequestStatistics.getResponseStatisticsList()) { assertThat(storeResponseStatistics).isNotNull(); RntbdChannelStatistics rntbdChannelStatistics = storeResponseStatistics .getStoreResult() .getStoreResponseDiagnostics() .getRntbdChannelStatistics(); assertThat(rntbdChannelStatistics).isNotNull(); try { String rntbdChannelStatisticsString = Utils.getSimpleObjectMapper().writeValueAsString(rntbdChannelStatistics); assertThat(rntbdChannelStatisticsString).contains("\"channelId\":\"" + rntbdChannelStatistics.getChannelId() + "\""); assertThat(rntbdChannelStatisticsString) .contains("\"channelTaskQueueSize\":" + rntbdChannelStatistics.getChannelTaskQueueSize()); assertThat(rntbdChannelStatisticsString) .contains("\"pendingRequestsCount\":" + rntbdChannelStatistics.getPendingRequestsCount()); assertThat(rntbdChannelStatisticsString) .contains("\"lastReadTime\":\"" + rntbdChannelStatistics.getLastReadTime() + "\""); if (rntbdChannelStatistics.getTransitTimeoutCount() > 0) { assertThat(rntbdChannelStatisticsString) .contains("\"transitTimeoutCount\":" + rntbdChannelStatistics.getTransitTimeoutCount()); assertThat(rntbdChannelStatisticsString) .contains("\"transitTimeoutStartingTime\":\"" + rntbdChannelStatistics.getTransitTimeoutStartingTime() + "\""); } else { assertThat(rntbdChannelStatisticsString) .doesNotContain("\"transitTimeoutCount\":" + rntbdChannelStatistics.getTransitTimeoutCount()); assertThat(rntbdChannelStatisticsString) .doesNotContain("\"transitTimeoutStartingTime\":\"" + rntbdChannelStatistics.getTransitTimeoutStartingTime() + "\""); } assertThat(rntbdChannelStatisticsString).contains("\"waitForConnectionInit\":" + rntbdChannelStatistics.isWaitForConnectionInit()); } catch (JsonProcessingException e) { fail("Failed to parse RntbdChannelStatistics"); } } } } private CosmosDiagnostics performDocumentOperation( CosmosAsyncContainer cosmosAsyncContainer, OperationType operationType, TestItem createdItem) { if (operationType == OperationType.Query) { String query = "SELECT * from c"; FeedResponse<TestItem> itemFeedResponse = cosmosAsyncContainer.queryItems(query, TestItem.class).byPage().blockFirst(); return itemFeedResponse.getCosmosDiagnostics(); } if (operationType == OperationType.Read) { return cosmosAsyncContainer .readItem(createdItem.id, new PartitionKey(createdItem.mypk), TestItem.class) .block() .getDiagnostics(); } if (operationType == OperationType.Replace) { return cosmosAsyncContainer .replaceItem(createdItem, createdItem.id, new PartitionKey(createdItem.mypk)) .block() .getDiagnostics(); } if (operationType == OperationType.Create) { return cosmosAsyncContainer.createItem(TestItem.createNewItem()).block().getDiagnostics(); } throw new IllegalArgumentException("The operation type is not supported"); } public static class TestItem { public String id; public String mypk; public TestItem() { } public TestItem(String id, String mypk) { this.id = id; this.mypk = mypk; } public static TestItem createNewItem() { return new TestItem(UUID.randomUUID().toString(), UUID.randomUUID().toString()); } } }
assertThat(queryDiagnostics).contains("endTimeUTC");
public void gatewayDiagnosticsOnException() throws Exception { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = null; try { createResponse = this.containerGateway.createItem(internalObjectNode); CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey")); CosmosItemResponse<InternalObjectNode> readResponse = this.containerGateway.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey("wrongPartitionKey"), InternalObjectNode.class); fail("request should fail as partition key is wrong"); } catch (CosmosException exception) { System.out.println(exception.getDiagnostics()); isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND); assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).contains("gatewayStatisticsList"); assertThat(diagnostics).contains("\"statusCode\":404"); assertThat(diagnostics).contains("\"operationType\":\"Read\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).contains("\"exceptionMessage\":\"Entity with the specified id does not exist in the system."); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(createResponse.getDiagnostics().getContactedRegionNames()).isNotNull(); validateRegionContacted(createResponse.getDiagnostics(), this.containerGateway.asyncContainer.getDatabase().getClient()); assertThat(createResponse.getDiagnostics().getRegionsContacted()).isNotEmpty(); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); validateTransportRequestTimelineGateway(diagnostics); isValidJSON(diagnostics); } }
class CosmosDiagnosticsTest extends TestSuiteBase { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final String USER_AGENT_SUFFIX_GATEWAY_CLIENT = "gatewayClientSuffix"; private static final String USER_AGENT_SUFFIX_DIRECT_CLIENT = "directClientSuffix"; private static final DateTimeFormatter RESPONSE_TIME_FORMATTER = DateTimeFormatter.ISO_INSTANT; private static final String tempMachineId = getTempMachineId(); private CosmosClient gatewayClient; private CosmosClient directClient; private CosmosAsyncDatabase cosmosAsyncDatabase; private CosmosContainer containerGateway; private CosmosContainer containerDirect; private CosmosAsyncContainer cosmosAsyncContainer; private String gatewayClientUserAgent; private String directClientUserAgent; private static String getTempMachineId() { Field field = null; try { field = RxDocumentClientImpl.class.getDeclaredField("tempMachineId"); } catch (NoSuchFieldException e) { fail(e.toString()); } field.setAccessible(true); try { return (String)field.get(null); } catch (IllegalAccessException e) { fail(e.toString()); return null; } } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { assertThat(this.gatewayClient).isNull(); gatewayClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .userAgentSuffix(USER_AGENT_SUFFIX_GATEWAY_CLIENT) .gatewayMode() .buildClient(); UserAgentContainer userAgentContainer = new UserAgentContainer(); userAgentContainer.setSuffix(USER_AGENT_SUFFIX_GATEWAY_CLIENT); this.gatewayClientUserAgent = userAgentContainer.getUserAgent(); directClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .userAgentSuffix(USER_AGENT_SUFFIX_DIRECT_CLIENT) .directMode() .buildClient(); userAgentContainer.setSuffix(USER_AGENT_SUFFIX_DIRECT_CLIENT); this.directClientUserAgent = userAgentContainer.getUserAgent(); cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(this.gatewayClient.asyncClient()); cosmosAsyncDatabase = directClient.asyncClient().getDatabase(cosmosAsyncContainer.getDatabase().getId()); containerGateway = gatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); containerDirect = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { if (this.gatewayClient != null) { this.gatewayClient.close(); } if (this.directClient != null) { this.directClient.close(); } } @DataProvider(name = "query") private Object[][] query() { return new Object[][]{ new Object[] { "Select * from c where c.id = 'wrongId'", true }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", true }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", true }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", true }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", true }, new Object[] { "Select * from c where c.id = 'wrongId'", false }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", false }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", false }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId'", false }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", false }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", false }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", false }, }; } @DataProvider(name = "readAllItemsOfLogicalPartition") private Object[][] readAllItemsOfLogicalPartition() { return new Object[][]{ new Object[] { 1, true }, new Object[] { 5, null }, new Object[] { 20, null }, new Object[] { 1, false }, new Object[] { 5, false }, new Object[] { 20, false }, }; } @DataProvider(name = "connectionStateListenerArgProvider") public Object[][] connectionStateListenerArgProvider() { return new Object[][]{ {true}, {false} }; } @DataProvider(name = "operationTypeProvider") public static Object[][] operationTypeProvider() { return new Object[][]{ { OperationType.Read }, { OperationType.Replace }, { OperationType.Create }, { OperationType.Query }, }; } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void gatewayDiagnostics() throws Exception { Thread.sleep(2000); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = containerGateway.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).contains("gatewayStatisticsList"); assertThat(diagnostics).contains("\"operationType\":\"Create\""); assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\""); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); assertThat(createResponse.getDiagnostics().getContactedRegionNames()).isNotNull(); assertThat(createResponse.getDiagnostics().getRegionsContacted()).isNotEmpty(); validateTransportRequestTimelineGateway(diagnostics); validateRegionContacted(createResponse.getDiagnostics(), gatewayClient.asyncClient()); isValidJSON(diagnostics); } @Test(groups = {"simple"}, timeOut = TIMEOUT)
class CosmosDiagnosticsTest extends TestSuiteBase { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final String USER_AGENT_SUFFIX_GATEWAY_CLIENT = "gatewayClientSuffix"; private static final String USER_AGENT_SUFFIX_DIRECT_CLIENT = "directClientSuffix"; private static final DateTimeFormatter RESPONSE_TIME_FORMATTER = DateTimeFormatter.ISO_INSTANT; private static final String tempMachineId = getTempMachineId(); private CosmosClient gatewayClient; private CosmosClient directClient; private CosmosAsyncDatabase cosmosAsyncDatabase; private CosmosContainer containerGateway; private CosmosContainer containerDirect; private CosmosAsyncContainer cosmosAsyncContainer; private String gatewayClientUserAgent; private String directClientUserAgent; private static String getTempMachineId() { Field field = null; try { field = RxDocumentClientImpl.class.getDeclaredField("tempMachineId"); } catch (NoSuchFieldException e) { fail(e.toString()); } field.setAccessible(true); try { return (String)field.get(null); } catch (IllegalAccessException e) { fail(e.toString()); return null; } } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { assertThat(this.gatewayClient).isNull(); gatewayClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .userAgentSuffix(USER_AGENT_SUFFIX_GATEWAY_CLIENT) .gatewayMode() .buildClient(); UserAgentContainer userAgentContainer = new UserAgentContainer(); userAgentContainer.setSuffix(USER_AGENT_SUFFIX_GATEWAY_CLIENT); this.gatewayClientUserAgent = userAgentContainer.getUserAgent(); directClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .userAgentSuffix(USER_AGENT_SUFFIX_DIRECT_CLIENT) .directMode() .buildClient(); userAgentContainer.setSuffix(USER_AGENT_SUFFIX_DIRECT_CLIENT); this.directClientUserAgent = userAgentContainer.getUserAgent(); cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(this.gatewayClient.asyncClient()); cosmosAsyncDatabase = directClient.asyncClient().getDatabase(cosmosAsyncContainer.getDatabase().getId()); containerGateway = gatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); containerDirect = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { if (this.gatewayClient != null) { this.gatewayClient.close(); } if (this.directClient != null) { this.directClient.close(); } } @DataProvider(name = "query") private Object[][] query() { return new Object[][]{ new Object[] { "Select * from c where c.id = 'wrongId'", true }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", true }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", true }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", true }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", true }, new Object[] { "Select * from c where c.id = 'wrongId'", false }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", false }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", false }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId'", false }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", false }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", false }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", false }, }; } @DataProvider(name = "readAllItemsOfLogicalPartition") private Object[][] readAllItemsOfLogicalPartition() { return new Object[][]{ new Object[] { 1, true }, new Object[] { 5, null }, new Object[] { 20, null }, new Object[] { 1, false }, new Object[] { 5, false }, new Object[] { 20, false }, }; } @DataProvider(name = "connectionStateListenerArgProvider") public Object[][] connectionStateListenerArgProvider() { return new Object[][]{ {true}, {false} }; } @DataProvider(name = "operationTypeProvider") public static Object[][] operationTypeProvider() { return new Object[][]{ { OperationType.Read }, { OperationType.Replace }, { OperationType.Create }, { OperationType.Query }, }; } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void gatewayDiagnostics() throws Exception { Thread.sleep(2000); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = containerGateway.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).contains("gatewayStatisticsList"); assertThat(diagnostics).contains("\"operationType\":\"Create\""); assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\""); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); assertThat(createResponse.getDiagnostics().getContactedRegionNames()).isNotNull(); assertThat(createResponse.getDiagnostics().getRegionsContacted()).isNotEmpty(); validateTransportRequestTimelineGateway(diagnostics); validateRegionContacted(createResponse.getDiagnostics(), gatewayClient.asyncClient()); isValidJSON(diagnostics); } @Test(groups = {"simple"}, timeOut = TIMEOUT) @Test(groups = {"simple"}, timeOut = TIMEOUT) public void systemDiagnosticsForSystemStateInformation() { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = this.containerGateway.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("systemInformation"); assertThat(diagnostics).contains("usedMemory"); assertThat(diagnostics).contains("availableMemory"); assertThat(diagnostics).contains("systemCpuLoad"); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnostics() throws Exception { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = containerDirect.createItem(internalObjectNode); validateDirectModeDiagnosticsOnSuccess(createResponse.getDiagnostics(), directClient, this.directClientUserAgent); try { containerDirect.createItem(internalObjectNode); fail("expected 409"); } catch (CosmosException e) { validateDirectModeDiagnosticsOnException(e, this.directClientUserAgent); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void requestSessionTokenDiagnostics() { CosmosClient testSessionTokenClient = null; try { testSessionTokenClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .consistencyLevel(ConsistencyLevel.SESSION) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer cosmosContainer = testSessionTokenClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"requestSessionToken\":null"); String sessionToken = createResponse.getSessionToken(); CosmosItemResponse<InternalObjectNode> readResponse = cosmosContainer.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey(BridgeInternal.getProperties(createResponse).getId()), InternalObjectNode.class); diagnostics = readResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"requestSessionToken\":\"%s\"", sessionToken)); CosmosBatch batch = CosmosBatch.createCosmosBatch(new PartitionKey( BridgeInternal.getProperties(createResponse).getId())); internalObjectNode = getInternalObjectNode(); batch.createItemOperation(internalObjectNode); CosmosBatchResponse batchResponse = cosmosContainer.executeCosmosBatch(batch, new CosmosBatchRequestOptions().setSessionToken(readResponse.getSessionToken())); diagnostics = batchResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"requestSessionToken\":\"%s\"", readResponse.getSessionToken())); } finally { if (testSessionTokenClient != null) { testSessionTokenClient.close(); } } } @Test(groups = {"simple"}) public void databaseAccountToClients() { CosmosClient testClient = null; try { testClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer cosmosContainer = testClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"clientEndpoints\"" + ":{\"%s\"", TestConfigurations.HOST)); int clientsIndex = diagnostics.indexOf("\"clientEndpoints\":"); String[] substrings = diagnostics.substring(clientsIndex, clientsIndex + 120) .split("}")[0].split(":"); String intString = substrings[substrings.length-1]; int intValue = Integer.parseInt(intString); CosmosClient testClient2 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); internalObjectNode = getInternalObjectNode(); createResponse = cosmosContainer.createItem(internalObjectNode); diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"clientEndpoints\"" + ":{\"%s\"", TestConfigurations.HOST)); clientsIndex = diagnostics.indexOf("\"clientEndpoints\":"); substrings = diagnostics.substring(clientsIndex, clientsIndex + 120) .split("}")[0].split(":"); intString = substrings[substrings.length-1]; assertThat(Integer.parseInt(intString)).isEqualTo(intValue+1); testClient2.close(); } finally { if (testClient != null) { testClient.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryPlanDiagnostics() throws JsonProcessingException { List<String> itemIdList = new ArrayList<>(); for(int i = 0; i< 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = containerDirect.createItem(internalObjectNode); if(i%20 == 0) { itemIdList.add(internalObjectNode.getId()); } } String queryDiagnostics = null; List<String> queryList = new ArrayList<>(); queryList.add("Select * from c"); StringBuilder queryBuilder = new StringBuilder("SELECT * from c where c.mypk in ("); for(int i = 0 ; i < itemIdList.size(); i++){ queryBuilder.append("'").append(itemIdList.get(i)).append("'"); if(i < (itemIdList.size()-1)) { queryBuilder.append(","); } else { queryBuilder.append(")"); } } queryList.add(queryBuilder.toString()); queryList.add("Select * from c where c.id = 'wrongId'"); for(String query : queryList) { int feedResponseCounter = 0; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setQueryMetricsEnabled(true); Iterator<FeedResponse<InternalObjectNode>> iterator = containerDirect.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); if (feedResponseCounter == 0) { assertThat(queryDiagnostics).contains("queryPlanDiagnosticsContext"); assertThat(queryDiagnostics).contains("startTimeUTC"); assertThat(queryDiagnostics).contains("endTimeUTC"); assertThat(queryDiagnostics).contains("durationInMilliSecs"); String requestTimeLine = OBJECT_MAPPER.writeValueAsString(feedResponse.getCosmosDiagnostics().getFeedResponseDiagnostics().getQueryPlanDiagnosticsContext().getRequestTimeline()); assertThat(requestTimeLine).contains("connectionConfigured"); assertThat(requestTimeLine).contains("requestSent"); assertThat(requestTimeLine).contains("transitTime"); assertThat(requestTimeLine).contains("received"); } else { assertThat(queryDiagnostics).contains("\"queryPlanDiagnosticsContext\":null"); } feedResponseCounter++; } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readManyDiagnostics() { String pkValue = UUID.randomUUID().toString(); PartitionKey partitionKey = new PartitionKey(pkValue); List<CosmosItemIdentity> itemIdList = new ArrayList<>(); for(int i = 0; i< 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(pkValue); CosmosItemResponse<InternalObjectNode> createResponse = containerDirect.createItem(internalObjectNode); if(i%20 == 0) { itemIdList.add(new CosmosItemIdentity(partitionKey, internalObjectNode.getId())); } } FeedResponse<InternalObjectNode> response = containerDirect.readMany(itemIdList, InternalObjectNode.class); FeedResponseDiagnostics diagnostics = response.getCosmosDiagnostics().getFeedResponseDiagnostics(); assertThat(diagnostics.getClientSideRequestStatistics().size()).isEqualTo(1); assertThat(diagnostics.getQueryMetricsMap().values().iterator().next().getRetrievedDocumentCount()).isEqualTo(itemIdList.size()); String cosmosDiagnosticsString = response.getCosmosDiagnostics().toString(); assertThat(cosmosDiagnosticsString).contains("\"userAgent\":\"" + this.directClientUserAgent + "\""); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryMetricsWithIndexMetrics() { List<String> itemIdList = new ArrayList<>(); for(int i = 0; i< 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = containerDirect.createItem(internalObjectNode); if(i%20 == 0) { itemIdList.add(internalObjectNode.getId()); } } String queryDiagnostics = null; List<String> queryList = new ArrayList<>(); StringBuilder queryBuilder = new StringBuilder("SELECT * from c where c.mypk in ("); for(int i = 0 ; i < itemIdList.size(); i++){ queryBuilder.append("'").append(itemIdList.get(i)).append("'"); if(i < (itemIdList.size()-1)) { queryBuilder.append(","); } else { queryBuilder.append(")"); } } queryList.add(queryBuilder.toString()); for (String query : queryList) { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setQueryMetricsEnabled(true); options.setIndexMetricsEnabled(true); Iterator<FeedResponse<InternalObjectNode>> iterator = containerDirect.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); logger.info("This is query diagnostics {}", queryDiagnostics); if (feedResponse.getResponseHeaders().containsKey(HttpConstants.HttpHeaders.INDEX_UTILIZATION)) { assertThat(feedResponse.getResponseHeaders().get(HttpConstants.HttpHeaders.INDEX_UTILIZATION)).isNotNull(); assertThat(createFromJSONString(Utils.decodeBase64String(feedResponse.getResponseHeaders().get(HttpConstants.HttpHeaders.INDEX_UTILIZATION))).getUtilizedSingleIndexes()).isNotNull(); } } } } @Test(groups = {"simple"}, dataProvider = "query", timeOut = TIMEOUT) public void queryMetrics(String query, Boolean qmEnabled) { CosmosContainer directContainer = this.directClient.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()) .getContainer(this.cosmosAsyncContainer.getId()); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); if (qmEnabled != null) { options.setQueryMetricsEnabled(qmEnabled); } boolean qroupByFirstResponse = true; Iterator<FeedResponse<InternalObjectNode>> iterator = directContainer.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); assertThat(iterator.hasNext()).isTrue(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); assertThat(feedResponse.getResults().size()).isEqualTo(0); if (!query.contains("group by") || qroupByFirstResponse) { validateQueryDiagnostics(queryDiagnostics, qmEnabled, true); validateDirectModeQueryDiagnostics(queryDiagnostics, this.directClientUserAgent); if (query.contains("group by")) { qroupByFirstResponse = false; } } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryDiagnosticsOnOrderBy() { String containerId = "testcontainer"; cosmosAsyncDatabase.createContainer(containerId, "/mypk", ThroughputProperties.createManualThroughput(40000)).block(); CosmosAsyncContainer testcontainer = cosmosAsyncDatabase.getContainer(containerId); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setConsistencyLevel(ConsistencyLevel.EVENTUAL); testcontainer.createItem(getInternalObjectNode()).block(); options.setMaxDegreeOfParallelism(-1); String query = "SELECT * from c ORDER BY c._ts DESC"; CosmosPagedFlux<InternalObjectNode> cosmosPagedFlux = testcontainer.queryItems(query, options, InternalObjectNode.class); Set<String> partitionKeyRangeIds = new HashSet<>(); Set<String> pkRids = new HashSet<>(); cosmosPagedFlux.byPage().flatMap(feedResponse -> { String cosmosDiagnosticsString = feedResponse.getCosmosDiagnostics().toString(); Pattern pattern = Pattern.compile("(\"partitionKeyRangeId\":\")(\\d)"); Matcher matcher = pattern.matcher(cosmosDiagnosticsString); while (matcher.find()) { String group = matcher.group(2); partitionKeyRangeIds.add(group); } pattern = Pattern.compile("(pkrId:)(\\d)"); matcher = pattern.matcher(cosmosDiagnosticsString); while (matcher.find()) { String group = matcher.group(2); pkRids.add(group); } return Flux.just(feedResponse); }).blockLast(); assertThat(pkRids).isNotEmpty(); assertThat(pkRids).isEqualTo(partitionKeyRangeIds); deleteCollection(testcontainer); } @Test(groups = {"simple"}, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) public void directDiagnosticsOnCancelledOperation(OperationType operationType) { CosmosAsyncClient client = null; FaultInjectionRule faultInjectionRule = null; try { client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(TestConfigurations.HOST) .endToEndOperationLatencyPolicyConfig( new CosmosEndToEndOperationLatencyPolicyConfigBuilder(Duration.ofSeconds(1)).build() ).buildAsyncClient(); CosmosAsyncContainer container = client.getDatabase(containerDirect.asyncContainer.getDatabase().getId()).getContainer(containerDirect.getId()); TestItem testItem = TestItem.createNewItem(); container.createItem(testItem).block(); faultInjectionRule = new FaultInjectionRuleBuilder("responseDelay") .condition(new FaultInjectionConditionBuilder().build()) .result( FaultInjectionResultBuilders.getResultBuilder(FaultInjectionServerErrorType.RESPONSE_DELAY) .delay(Duration.ofSeconds(2)) .build() ) .build(); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(faultInjectionRule)).block(); this.performDocumentOperation(container, operationType, testItem); fail("expected OperationCancelledException"); } catch (CosmosException e) { assertThat(e).isInstanceOf(OperationCancelledException.class); String cosmosDiagnosticsString = e.getDiagnostics().toString(); assertThat(cosmosDiagnosticsString).contains("\"statusCode\":408"); assertThat(cosmosDiagnosticsString).contains("\"subStatusCode\":20008"); } finally { if (faultInjectionRule != null) { faultInjectionRule.disable(); } safeClose(client); } } @Test(groups = {"simple"}, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) public void directDiagnostics_WithFaultInjection(OperationType operationType) { CosmosAsyncClient client = null; FaultInjectionRule faultInjectionRule = null; try { client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(TestConfigurations.HOST) .buildAsyncClient(); CosmosAsyncContainer container = client.getDatabase(containerDirect.asyncContainer.getDatabase().getId()).getContainer(containerDirect.getId()); TestItem testItem = TestItem.createNewItem(); container.createItem(testItem).block(); faultInjectionRule = new FaultInjectionRuleBuilder("serverResponseError") .condition(new FaultInjectionConditionBuilder().build()) .result( FaultInjectionResultBuilders.getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .build(); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(faultInjectionRule)).block(); CosmosDiagnostics cosmosDiagnostics = this.performDocumentOperation(container, operationType, testItem); assertThat(cosmosDiagnostics).isNotNull(); String diagnosticsString = cosmosDiagnostics.toString(); assertThat(diagnosticsString).contains("\"statusCode\":410"); assertThat(diagnosticsString).contains("\"subStatusCode\":21005"); assertThat(diagnosticsString).doesNotContain("\"statusCode\":408"); assertThat(diagnosticsString).doesNotContain("\"subStatusCode\":20008"); } catch (CosmosException e) { fail("Request should succeeded but failed with " + e.getMessage()); } finally { if (faultInjectionRule != null) { faultInjectionRule.disable(); } safeClose(client); } } private void validateDirectModeDiagnosticsOnSuccess( CosmosDiagnostics cosmosDiagnostics, CosmosClient testDirectClient, String userAgent) throws Exception { String diagnostics = cosmosDiagnostics.toString(); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("supplementalResponseStatisticsList"); assertThat(diagnostics).contains("gatewayStatisticsList"); assertThat(diagnostics).contains("addressResolutionStatistics"); assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\""); assertThat(diagnostics).contains("\"metaDataName\":\"PARTITION_KEY_RANGE_LOOK_UP\""); assertThat(diagnostics).contains("\"metaDataName\":\"SERVER_ADDRESS_LOOKUP\""); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + userAgent + "\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"backendLatencyInMs\""); assertThat(diagnostics).contains("\"retryAfterInMs\""); assertThat(diagnostics).contains("\"channelStatistics\""); assertThat(cosmosDiagnostics.getContactedRegionNames()).isNotEmpty(); assertThat(cosmosDiagnostics.getDuration()).isNotNull(); validateTransportRequestTimelineDirect(diagnostics); validateRegionContacted(cosmosDiagnostics, testDirectClient.asyncClient()); validateChannelStatistics(cosmosDiagnostics); isValidJSON(diagnostics); } private void validateDirectModeDiagnosticsOnException(CosmosException cosmosException, String userAgent) { CosmosDiagnostics cosmosDiagnostics = cosmosException.getDiagnostics(); String diagnosticsString = cosmosDiagnostics.toString(); assertThat(diagnosticsString).contains("\"backendLatencyInMs\""); assertThat(diagnosticsString).contains("\"userAgent\":\"" + userAgent + "\""); assertThat(diagnosticsString).contains("\"retryAfterInMs\""); assertThat(diagnosticsString).contains("\"exceptionMessage\":\"[\\\"Resource with specified id or name already exists.\\\"]\""); assertThat(diagnosticsString).contains("\"exceptionResponseHeaders\""); assertThat(diagnosticsString).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); validateTransportRequestTimelineDirect(diagnosticsString); validateChannelStatistics(cosmosDiagnostics); if (!(cosmosException instanceof OperationCancelledException)) { assertThat(diagnosticsString).doesNotContain("\"statusCode\":408"); assertThat(diagnosticsString).doesNotContain("\"subStatusCode\":20008"); } } private void validateDirectModeQueryDiagnostics(String diagnostics, String userAgent) { assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("supplementalResponseStatisticsList"); assertThat(diagnostics).contains("responseStatisticsList"); assertThat(diagnostics).contains("gatewayStatisticsList"); assertThat(diagnostics).contains("addressResolutionStatistics"); assertThat(diagnostics).contains("\"userAgent\":\"" + userAgent + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); } private void validateGatewayModeQueryDiagnostics(String diagnostics, String userAgent) { assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).contains(("gatewayStatisticsList")); assertThat(diagnostics).contains("\"operationType\":\"Query\""); assertThat(diagnostics).contains("\"userAgent\":\"" + userAgent + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"regionsContacted\""); } @Test(groups = {"simple"}, dataProvider = "query", timeOut = TIMEOUT*2) public void queryDiagnosticsGatewayMode(String query, Boolean qmEnabled) { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); List<String> itemIdList = new ArrayList<>(); for (int i = 0; i < 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); containerGateway.createItem(internalObjectNode); if (i % 20 == 0) { itemIdList.add(internalObjectNode.getId()); } } boolean qroupByFirstResponse = true; if (qmEnabled != null) { options.setQueryMetricsEnabled(qmEnabled); } Iterator<FeedResponse<InternalObjectNode>> iterator = containerGateway .queryItems(query, options, InternalObjectNode.class) .iterableByPage() .iterator(); assertThat(iterator.hasNext()).isTrue(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); assertThat(feedResponse.getResults().size()).isEqualTo(0); if (!query.contains("group by") || qroupByFirstResponse) { validateQueryDiagnostics(queryDiagnostics, qmEnabled, true); validateGatewayModeQueryDiagnostics(queryDiagnostics, this.gatewayClientUserAgent); if (query.contains("group by")) { qroupByFirstResponse = false; } } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryMetricsWithADifferentLocale() { Locale.setDefault(Locale.GERMAN); String query = "select * from root where root.id= \"someid\""; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); Iterator<FeedResponse<InternalObjectNode>> iterator = this.containerGateway.queryItems(query, options, InternalObjectNode.class) .iterableByPage().iterator(); double requestCharge = 0; while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); requestCharge += feedResponse.getRequestCharge(); } assertThat(requestCharge).isGreaterThan(0); Locale.setDefault(Locale.ROOT); } private static void validateQueryDiagnostics( String queryDiagnostics, Boolean qmEnabled, boolean expectQueryPlanDiagnostics) { if (qmEnabled == null || qmEnabled) { assertThat(queryDiagnostics).contains("retrievedDocumentCount"); assertThat(queryDiagnostics).contains("queryPreparationTimes"); assertThat(queryDiagnostics).contains("runtimeExecutionTimes"); assertThat(queryDiagnostics).contains("fetchExecutionRanges"); } else { assertThat(queryDiagnostics).doesNotContain("retrievedDocumentCount"); assertThat(queryDiagnostics).doesNotContain("queryPreparationTimes"); assertThat(queryDiagnostics).doesNotContain("runtimeExecutionTimes"); assertThat(queryDiagnostics).doesNotContain("fetchExecutionRanges"); } if (expectQueryPlanDiagnostics) { assertThat(queryDiagnostics).contains("queryPlanDiagnosticsContext"); assertThat(queryDiagnostics).contains("startTimeUTC"); assertThat(queryDiagnostics).contains("endTimeUTC"); } else { assertThat(queryDiagnostics).contains("\"queryPlanDiagnosticsContext\":null"); } } @Test(groups = {"simple"}, dataProvider = "readAllItemsOfLogicalPartition", timeOut = TIMEOUT) public void queryMetricsForReadAllItemsOfLogicalPartition(Integer expectedItemCount, Boolean qmEnabled) { String pkValue = UUID.randomUUID().toString(); for (int i = 0; i < expectedItemCount; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(pkValue); CosmosItemResponse<InternalObjectNode> createResponse = containerGateway.createItem(internalObjectNode); } CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); if (qmEnabled != null) { options = options.setQueryMetricsEnabled(qmEnabled); } ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(options, 5); Iterator<FeedResponse<InternalObjectNode>> iterator = this.containerGateway .readAllItems( new PartitionKey(pkValue), options, InternalObjectNode.class) .iterableByPage().iterator(); assertThat(iterator.hasNext()).isTrue(); int actualItemCount = 0; while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); actualItemCount += feedResponse.getResults().size(); validateQueryDiagnostics(queryDiagnostics, qmEnabled, false); } assertThat(actualItemCount).isEqualTo(expectedItemCount); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnosticsOnException() throws Exception { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = null; try { createResponse = containerDirect.createItem(internalObjectNode); CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey")); CosmosItemResponse<InternalObjectNode> readResponse = containerDirect.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey("wrongPartitionKey"), InternalObjectNode.class); fail("request should fail as partition key is wrong"); } catch (CosmosException exception) { isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.directClientUserAgent + "\""); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(exception.getDiagnostics().getContactedRegionNames()).isNotEmpty(); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); assertThat(diagnostics).contains("\"backendLatencyInMs\""); assertThat(diagnostics).contains("\"retryAfterInMs\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"exceptionMessage\":\"[\\\"Resource Not Found."); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\":null"); isValidJSON(diagnostics); validateTransportRequestTimelineDirect(diagnostics); validateRegionContacted(createResponse.getDiagnostics(), directClient.asyncClient()); ObjectNode diagnosticsNode = (ObjectNode) OBJECT_MAPPER.readTree(diagnostics); JsonNode responseStatisticsList = diagnosticsNode.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); assertThat(responseStatisticsList.size()).isGreaterThan(0); JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); assertThat(storeResult).isNotNull(); JsonNode replicaStatusList = storeResult.get("replicaStatusList"); assertThat(replicaStatusList.isArray()).isTrue(); assertThat(replicaStatusList.size()).isGreaterThan(0); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnosticsOnMetadataException() { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosClient client = null; try { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer container = client.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); HttpClient mockHttpClient = Mockito.mock(HttpClient.class); Mockito.when(mockHttpClient.send(Mockito.any(HttpRequest.class), Mockito.any(Duration.class))) .thenReturn(Mono.error(new CosmosException(400, "TestBadRequest"))); RxStoreModel rxGatewayStoreModel = rxGatewayStoreModel = ReflectionUtils.getGatewayProxy((RxDocumentClientImpl) client.asyncClient().getDocClientWrapper()); ReflectionUtils.setGatewayHttpClient(rxGatewayStoreModel, mockHttpClient); container.createItem(internalObjectNode); fail("request should fail as bad request"); } catch (CosmosException exception) { isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.BADREQUEST); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("\"exceptionMessage\":\"TestBadRequest\""); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(diagnostics).contains("\"resourceType\":\"DocumentCollection\""); assertThat(exception.getDiagnostics().getContactedRegionNames()).isNotEmpty(); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); isValidJSON(diagnostics); } finally { if (client != null) { client.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void supplementalResponseStatisticsList() throws Exception { ClientSideRequestStatistics clientSideRequestStatistics = new ClientSideRequestStatistics(mockDiagnosticsClientContext()); for (int i = 0; i < 15; i++) { RxDocumentServiceRequest rxDocumentServiceRequest = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Head, ResourceType.Document); clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, null, null); } List<ClientSideRequestStatistics.StoreResponseStatistics> storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); ObjectMapper objectMapper = new ObjectMapper(); String diagnostics = objectMapper.writeValueAsString(clientSideRequestStatistics); JsonNode jsonNode = objectMapper.readTree(diagnostics); ArrayNode supplementalResponseStatisticsListNode = (ArrayNode) jsonNode.get("supplementalResponseStatisticsList"); assertThat(storeResponseStatistics.size()).isEqualTo(15); assertThat(supplementalResponseStatisticsListNode.size()).isEqualTo(10); clearStoreResponseStatistics(clientSideRequestStatistics); storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); assertThat(storeResponseStatistics.size()).isEqualTo(0); for (int i = 0; i < 7; i++) { RxDocumentServiceRequest rxDocumentServiceRequest = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Head, ResourceType.Document); clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, null, null); } storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); objectMapper = new ObjectMapper(); diagnostics = objectMapper.writeValueAsString(clientSideRequestStatistics); jsonNode = objectMapper.readTree(diagnostics); supplementalResponseStatisticsListNode = (ArrayNode) jsonNode.get("supplementalResponseStatisticsList"); assertThat(storeResponseStatistics.size()).isEqualTo(7); assertThat(supplementalResponseStatisticsListNode.size()).isEqualTo(7); for(JsonNode node : supplementalResponseStatisticsListNode) { assertThat(node.get("storeResult").asText()).isNotNull(); String requestResponseTimeUTC = node.get("requestResponseTimeUTC").asText(); Instant instant = Instant.from(RESPONSE_TIME_FORMATTER.parse(requestResponseTimeUTC)); assertThat(Instant.now().toEpochMilli() - instant.toEpochMilli()).isLessThan(5000); assertThat(node.get("requestResponseTimeUTC")).isNotNull(); assertThat(node.get("requestOperationType")).isNotNull(); assertThat(node.get("requestSessionToken")).isNotNull(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void serializationOnVariousScenarios() { CosmosDatabaseResponse cosmosDatabase = gatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).read(); String diagnostics = cosmosDatabase.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"DATABASE_DESERIALIZATION\""); CosmosContainerResponse containerResponse = this.containerGateway.read(); diagnostics = containerResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"CONTAINER_DESERIALIZATION\""); TestItem testItem = new TestItem(); testItem.id = "TestId"; testItem.mypk = "TestPk"; CosmosItemResponse<TestItem> itemResponse = this.containerGateway.createItem(testItem); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); testItem.id = "TestId2"; testItem.mypk = "TestPk"; itemResponse = this.containerGateway.createItem(testItem, new PartitionKey("TestPk"), null); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).doesNotContain("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).doesNotContain("\"serializationType\":\"ITEM_DESERIALIZATION\""); TestItem readTestItem = itemResponse.getItem(); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"ITEM_DESERIALIZATION\""); CosmosItemResponse<InternalObjectNode> readItemResponse = this.containerGateway.readItem(testItem.id, new PartitionKey(testItem.mypk), null, InternalObjectNode.class); InternalObjectNode properties = readItemResponse.getItem(); diagnostics = readItemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"ITEM_DESERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void rntbdRequestResponseLengthStatistics() throws Exception { TestItem testItem = new TestItem(); testItem.id = UUID.randomUUID().toString(); testItem.mypk = UUID.randomUUID().toString(); int testItemLength = OBJECT_MAPPER.writeValueAsBytes(testItem).length; CosmosContainer container = directClient.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()).getContainer(this.cosmosAsyncContainer.getId()); CosmosItemResponse<TestItem> createItemResponse = container.createItem(testItem); validate(createItemResponse.getDiagnostics(), testItemLength, ModelBridgeInternal.getPayloadLength(createItemResponse)); try { container.createItem(testItem); fail("expected to fail due to 409"); } catch (CosmosException e) { logger.info("Diagnostics are : {}", e.getDiagnostics()); String diagnostics = e.getDiagnostics().toString(); assertThat(diagnostics).contains("\"exceptionMessage\":\"[\\\"Resource with specified id or name already exists.\\\"]\""); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); validate(e.getDiagnostics(), testItemLength, 0); } CosmosItemResponse<TestItem> readItemResponse = container.readItem(testItem.id, new PartitionKey(testItem.mypk), TestItem.class); validate(readItemResponse.getDiagnostics(), 0, ModelBridgeInternal.getPayloadLength(readItemResponse)); CosmosItemResponse<Object> deleteItemResponse = container.deleteItem(testItem, null); validate(deleteItemResponse.getDiagnostics(), 0, 0); } @Test(groups = {"simple"}, dataProvider = "connectionStateListenerArgProvider", timeOut = TIMEOUT) public void rntbdStatistics(boolean connectionStateListenerEnabled) throws Exception { Instant beforeClientInitialization = Instant.now(); CosmosClient client1 = null; try { DirectConnectionConfig connectionConfig = DirectConnectionConfig.getDefaultConfig(); connectionConfig.setConnectionEndpointRediscoveryEnabled(connectionStateListenerEnabled); client1 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(connectionConfig) .buildClient(); TestItem testItem = new TestItem(); testItem.id = UUID.randomUUID().toString(); testItem.mypk = UUID.randomUUID().toString(); int testItemLength = OBJECT_MAPPER.writeValueAsBytes(testItem).length; CosmosContainer container = client1.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()).getContainer(this.cosmosAsyncContainer.getId()); Thread.sleep(1000); Instant beforeInitializingRntbdServiceEndpoint = Instant.now(); CosmosItemResponse<TestItem> operation1Response = container.upsertItem(testItem); Instant afterInitializingRntbdServiceEndpoint = Instant.now(); Thread.sleep(1000); Instant beforeOperation2 = Instant.now(); CosmosItemResponse<TestItem> operation2Response = container.upsertItem(testItem); Instant afterOperation2 = Instant.now(); Thread.sleep(1000); Instant beforeOperation3 = Instant.now(); CosmosItemResponse<TestItem> operation3Response = container.upsertItem(testItem); Instant afterOperation3 = Instant.now(); validateRntbdStatistics(operation3Response.getDiagnostics(), beforeClientInitialization, beforeInitializingRntbdServiceEndpoint, afterInitializingRntbdServiceEndpoint, beforeOperation2, afterOperation2, beforeOperation3, afterOperation3, connectionStateListenerEnabled); CosmosItemResponse<TestItem> readItemResponse = container.readItem(testItem.id, new PartitionKey(testItem.mypk), TestItem.class); validate(readItemResponse.getDiagnostics(), 0, ModelBridgeInternal.getPayloadLength(readItemResponse)); CosmosItemResponse<Object> deleteItemResponse = container.deleteItem(testItem, null); validate(deleteItemResponse.getDiagnostics(), 0, 0); } finally { LifeCycleUtils.closeQuietly(client1); } } private void validateRntbdStatistics(CosmosDiagnostics cosmosDiagnostics, Instant clientInitializationTime, Instant beforeInitializingRntbdServiceEndpoint, Instant afterInitializingRntbdServiceEndpoint, Instant beforeOperation2, Instant afterOperation2, Instant beforeOperation3, Instant afterOperation3, boolean connectionStateListenerEnabled) throws Exception { ObjectNode diagnostics = (ObjectNode) OBJECT_MAPPER.readTree(cosmosDiagnostics.toString()); JsonNode responseStatisticsList = diagnostics.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); assertThat(responseStatisticsList.size()).isGreaterThan(0); JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); assertThat(storeResult).isNotNull(); JsonNode replicaStatusList = storeResult.get("replicaStatusList"); assertThat(replicaStatusList.isArray()).isTrue(); assertThat(replicaStatusList.size()).isGreaterThan(0); JsonNode serviceEndpointStatistics = storeResult.get("serviceEndpointStatistics"); assertThat(serviceEndpointStatistics).isNotNull(); assertThat(serviceEndpointStatistics.get("availableChannels").asInt(-1)).isGreaterThan(0); assertThat(serviceEndpointStatistics.get("acquiredChannels").asInt(-1)).isEqualTo(0); assertThat(serviceEndpointStatistics.get("inflightRequests").asInt(-1)).isEqualTo(1); assertThat(serviceEndpointStatistics.get("isClosed").asBoolean()).isEqualTo(false); JsonNode channelStatistics = storeResult.get("channelStatistics"); assertThat(channelStatistics).isNotNull(); assertThat(channelStatistics.get("channelId").asText()).isNotEmpty(); assertThat(channelStatistics.get("channelTaskQueueSize").asInt(-1)).isGreaterThanOrEqualTo(0); assertThat(channelStatistics.get("pendingRequestsCount").asInt(-1)).isGreaterThanOrEqualTo(0); assertThat(channelStatistics.get("lastReadTime").asText()).isNotEmpty(); assertThat(channelStatistics.get("waitForConnectionInit").asText()).isNotEmpty(); JsonNode connectionStateListenerMetrics = serviceEndpointStatistics.get("cerMetrics"); if (connectionStateListenerEnabled) { assertThat(connectionStateListenerMetrics).isNotNull(); assertThat(connectionStateListenerMetrics.get("lastCallTimestamp")).isNull(); assertThat(connectionStateListenerMetrics.get("lastActionableContext")).isNull(); } else { assertThat(connectionStateListenerMetrics).isNull(); } Instant beforeInitializationThreshold = beforeInitializingRntbdServiceEndpoint.minusMillis(1); assertThat(Instant.parse(serviceEndpointStatistics.get("createdTime").asText())) .isAfterOrEqualTo(beforeInitializationThreshold); Instant afterInitializationThreshold = afterInitializingRntbdServiceEndpoint.plusMillis(2); assertThat(Instant.parse(serviceEndpointStatistics.get("createdTime").asText())) .isBeforeOrEqualTo(afterInitializationThreshold); Instant afterOperation2Threshold = afterOperation2.plusMillis(2); Instant beforeOperation2Threshold = beforeOperation2.minusMillis(2); assertThat(Instant.parse(serviceEndpointStatistics.get("lastRequestTime").asText())) .isAfterOrEqualTo(beforeOperation2Threshold.toString()) .isBeforeOrEqualTo(afterOperation2Threshold.toString()); assertThat(Instant.parse(serviceEndpointStatistics.get("lastSuccessfulRequestTime").asText())) .isAfterOrEqualTo(beforeOperation2Threshold.toString()) .isBeforeOrEqualTo(afterOperation2Threshold.toString()); } private void validate(CosmosDiagnostics cosmosDiagnostics, int expectedRequestPayloadSize, int expectedResponsePayloadSize) throws Exception { ObjectNode diagnostics = (ObjectNode) OBJECT_MAPPER.readTree(cosmosDiagnostics.toString()); JsonNode responseStatisticsList = diagnostics.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); assertThat(responseStatisticsList.size()).isGreaterThan(0); JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); boolean hasPayload = storeResult.get("exceptionMessage") == null; assertThat(storeResult).isNotNull(); assertThat(storeResult.get("rntbdRequestLengthInBytes").asInt(-1)).isGreaterThan(expectedRequestPayloadSize); assertThat(storeResult.get("rntbdRequestLengthInBytes").asInt(-1)).isGreaterThan(expectedRequestPayloadSize); assertThat(storeResult.get("requestPayloadLengthInBytes").asInt(-1)).isEqualTo(expectedRequestPayloadSize); if (hasPayload) { assertThat(storeResult.get("responsePayloadLengthInBytes").asInt(-1)).isEqualTo(expectedResponsePayloadSize); } assertThat(storeResult.get("rntbdResponseLengthInBytes").asInt(-1)).isGreaterThan(expectedResponsePayloadSize); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void addressResolutionStatistics() { CosmosClient client1 = null; CosmosClient client2 = null; String databaseId = DatabaseForTest.generateId(); String containerId = UUID.randomUUID().toString(); CosmosDatabase cosmosDatabase = null; CosmosContainer cosmosContainer = null; try { client1 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); client1.createDatabase(databaseId); cosmosDatabase = client1.getDatabase(databaseId); cosmosDatabase.createContainer(containerId, "/mypk"); InternalObjectNode internalObjectNode = getInternalObjectNode(); cosmosContainer = cosmosDatabase.getContainer(containerId); CosmosItemResponse<InternalObjectNode> writeResourceResponse = cosmosContainer.createItem(internalObjectNode); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("addressResolutionStatistics"); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("\"inflightRequest\":false"); assertThat(writeResourceResponse.getDiagnostics().toString()).doesNotContain("endTime=\"null\""); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("\"exceptionMessage\":null"); client2 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); cosmosDatabase = client2.getDatabase(databaseId); cosmosContainer = cosmosDatabase.getContainer(containerId); AsyncDocumentClient asyncDocumentClient = client2.asyncClient().getContextClient(); GlobalAddressResolver addressResolver = (GlobalAddressResolver) FieldUtils.readField(asyncDocumentClient, "addressResolver", true); @SuppressWarnings("rawtypes") Map addressCacheByEndpoint = (Map) FieldUtils.readField(addressResolver, "addressCacheByEndpoint", true); Object endpointCache = addressCacheByEndpoint.values().toArray()[0]; GatewayAddressCache addressCache = (GatewayAddressCache) FieldUtils.readField(endpointCache, "addressCache", true); HttpClient httpClient = httpClient(true); FieldUtils.writeField(addressCache, "httpClient", httpClient, true); new Thread(() -> { try { Thread.sleep(5000); HttpClient httpClient1 = httpClient(false); FieldUtils.writeField(addressCache, "httpClient", httpClient1, true); } catch (Exception e) { fail(e.getMessage()); } }).start(); PartitionKey partitionKey = new PartitionKey(internalObjectNode.get("mypk")); CosmosItemResponse<InternalObjectNode> readResourceResponse = cosmosContainer.readItem(internalObjectNode.getId(), partitionKey, new CosmosItemRequestOptions(), InternalObjectNode.class); assertThat(readResourceResponse.getDiagnostics().toString()).contains("addressResolutionStatistics"); assertThat(readResourceResponse.getDiagnostics().toString()).contains("\"inflightRequest\":false"); assertThat(readResourceResponse.getDiagnostics().toString()).doesNotContain("endTime=\"null\""); assertThat(readResourceResponse.getDiagnostics().toString()).contains("\"exceptionMessage\":\"io.netty" + ".channel.AbstractChannel$AnnotatedConnectException: Connection refused"); } catch (Exception ex) { logger.error("Error in test addressResolutionStatistics", ex); fail("This test should not throw exception " + ex); } finally { safeDeleteSyncDatabase(cosmosDatabase); if (client1 != null) { client1.close(); } if (client2 != null) { client2.close(); } } } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void responseStatisticRequestStartTimeUTCForDirectCall() { CosmosAsyncClient client = null; String databaseId = DatabaseForTest.generateId(); FaultInjectionRule faultInjectionRule = null; try { client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(TestConfigurations.HOST) .endToEndOperationLatencyPolicyConfig( new CosmosEndToEndOperationLatencyPolicyConfigBuilder(Duration.ofSeconds(2)).build() ).buildAsyncClient(); createDatabase(client, databaseId); CosmosAsyncContainer container = createCollection(client, databaseId, getCollectionDefinition()); TestItem testItem = TestItem.createNewItem(); container.createItem(testItem).block(); faultInjectionRule = new FaultInjectionRuleBuilder("PARTITION_IS_MIGRATING") .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.CREATE_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.PARTITION_IS_MIGRATING) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(faultInjectionRule)).block(); CosmosDiagnostics cosmosDiagnostics = null; try { cosmosDiagnostics = container.createItem(TestItem.createNewItem()) .block() .getDiagnostics(); } catch (Exception exception) { fail("Request should succeeded, but failed with " + exception); } List<ClientSideRequestStatistics> clientSideRequestStatistics = (List<ClientSideRequestStatistics>) cosmosDiagnostics.getClientSideRequestStatistics(); List<ClientSideRequestStatistics.StoreResponseStatistics> responseStatistic = clientSideRequestStatistics.get(0).getResponseStatisticsList(); assert responseStatistic.size() == 2; Instant firstRequestStartTime = responseStatistic.get(0).getRequestStartTimeUTC(); Instant secondRequestStartTime = responseStatistic.get(1).getRequestStartTimeUTC(); assert firstRequestStartTime != null && secondRequestStartTime != null; assert firstRequestStartTime != secondRequestStartTime; assert firstRequestStartTime.compareTo(secondRequestStartTime) < 0; } finally { if (faultInjectionRule != null) { faultInjectionRule.disable(); } safeClose(client); } } private InternalObjectNode getInternalObjectNode() { InternalObjectNode internalObjectNode = new InternalObjectNode(); String uuid = UUID.randomUUID().toString(); internalObjectNode.setId(uuid); BridgeInternal.setProperty(internalObjectNode, "mypk", uuid); return internalObjectNode; } private InternalObjectNode getInternalObjectNode(String pkValue) { InternalObjectNode internalObjectNode = new InternalObjectNode(); String uuid = UUID.randomUUID().toString(); internalObjectNode.setId(uuid); BridgeInternal.setProperty(internalObjectNode, "mypk", pkValue); return internalObjectNode; } private List<ClientSideRequestStatistics.StoreResponseStatistics> getStoreResponseStatistics(ClientSideRequestStatistics requestStatistics) throws Exception { Field storeResponseStatisticsField = ClientSideRequestStatistics.class.getDeclaredField("supplementalResponseStatisticsList"); storeResponseStatisticsField.setAccessible(true); @SuppressWarnings({"unchecked"}) List<ClientSideRequestStatistics.StoreResponseStatistics> list = (List<ClientSideRequestStatistics.StoreResponseStatistics>) storeResponseStatisticsField.get(requestStatistics); return list; } private void clearStoreResponseStatistics(ClientSideRequestStatistics requestStatistics) throws Exception { Field storeResponseStatisticsField = ClientSideRequestStatistics.class.getDeclaredField("supplementalResponseStatisticsList"); storeResponseStatisticsField.setAccessible(true); storeResponseStatisticsField.set(requestStatistics, new ArrayList<ClientSideRequestStatistics.StoreResponseStatistics>()); } private void validateTransportRequestTimelineGateway(String diagnostics) { assertThat(diagnostics).contains("\"eventName\":\"connectionConfigured\""); assertThat(diagnostics).contains("\"eventName\":\"requestSent\""); assertThat(diagnostics).contains("\"eventName\":\"transitTime\""); assertThat(diagnostics).contains("\"eventName\":\"received\""); } private void validateTransportRequestTimelineDirect(String diagnostics) { assertThat(diagnostics).contains("\"eventName\":\"created\""); assertThat(diagnostics).contains("\"eventName\":\"queued\""); assertThat(diagnostics).contains("\"eventName\":\"channelAcquisitionStarted\""); assertThat(diagnostics).contains("\"eventName\":\"pipelined\""); assertThat(diagnostics).contains("\"eventName\":\"transitTime\""); assertThat(diagnostics).contains("\"eventName\":\"decodeTime"); assertThat(diagnostics).contains("\"eventName\":\"received\""); assertThat(diagnostics).contains("\"eventName\":\"completed\""); assertThat(diagnostics).contains("\"startTimeUTC\""); assertThat(diagnostics).contains("\"durationInMilliSecs\""); } public void isValidJSON(final String json) { try { final JsonParser parser = new JsonFactory().createParser(json); while (parser.nextToken() != null) { } } catch (IOException ex) { fail("Diagnostic string is not in json format ", ex); } } private HttpClient httpClient(boolean fakeProxy) { HttpClientConfig httpClientConfig; if(fakeProxy) { httpClientConfig = new HttpClientConfig(new Configs()) .withProxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 8888))); } else { httpClientConfig = new HttpClientConfig(new Configs()); } return HttpClient.createFixed(httpClientConfig); } private IndexUtilizationInfo createFromJSONString(String jsonString) { ObjectMapper indexUtilizationInfoObjectMapper = new ObjectMapper(); IndexUtilizationInfo indexUtilizationInfo = null; try { indexUtilizationInfo = indexUtilizationInfoObjectMapper.readValue(jsonString, IndexUtilizationInfo.class); } catch (JsonProcessingException e) { logger.error("Json not correctly formed ", e); } return indexUtilizationInfo; } private void validateRegionContacted(CosmosDiagnostics cosmosDiagnostics, CosmosAsyncClient cosmosAsyncClient) throws Exception { RxDocumentClientImpl rxDocumentClient = (RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(cosmosAsyncClient); GlobalEndpointManager globalEndpointManager = ReflectionUtils.getGlobalEndpointManager(rxDocumentClient); LocationCache locationCache = ReflectionUtils.getLocationCache(globalEndpointManager); Field locationInfoField = LocationCache.class.getDeclaredField("locationInfo"); locationInfoField.setAccessible(true); Object locationInfo = locationInfoField.get(locationCache); Class<?> DatabaseAccountLocationsInfoClass = Class.forName("com.azure.cosmos.implementation.routing" + ".LocationCache$DatabaseAccountLocationsInfo"); Field availableWriteEndpointByLocation = DatabaseAccountLocationsInfoClass.getDeclaredField( "availableWriteEndpointByLocation"); availableWriteEndpointByLocation.setAccessible(true); @SuppressWarnings("unchecked") Map<String, URI> map = (Map<String, URI>) availableWriteEndpointByLocation.get(locationInfo); String regionName = map.keySet().iterator().next(); assertThat(cosmosDiagnostics.getContactedRegionNames().size()).isEqualTo(1); assertThat(cosmosDiagnostics.getContactedRegionNames().iterator().next()).isEqualTo(regionName.toLowerCase()); } private void validateChannelStatistics(CosmosDiagnostics cosmosDiagnostics) { for (ClientSideRequestStatistics clientSideRequestStatistics : cosmosDiagnostics.getClientSideRequestStatistics()) { for (ClientSideRequestStatistics.StoreResponseStatistics storeResponseStatistics : clientSideRequestStatistics.getResponseStatisticsList()) { assertThat(storeResponseStatistics).isNotNull(); RntbdChannelStatistics rntbdChannelStatistics = storeResponseStatistics .getStoreResult() .getStoreResponseDiagnostics() .getRntbdChannelStatistics(); assertThat(rntbdChannelStatistics).isNotNull(); try { String rntbdChannelStatisticsString = Utils.getSimpleObjectMapper().writeValueAsString(rntbdChannelStatistics); assertThat(rntbdChannelStatisticsString).contains("\"channelId\":\"" + rntbdChannelStatistics.getChannelId() + "\""); assertThat(rntbdChannelStatisticsString) .contains("\"channelTaskQueueSize\":" + rntbdChannelStatistics.getChannelTaskQueueSize()); assertThat(rntbdChannelStatisticsString) .contains("\"pendingRequestsCount\":" + rntbdChannelStatistics.getPendingRequestsCount()); assertThat(rntbdChannelStatisticsString) .contains("\"lastReadTime\":\"" + rntbdChannelStatistics.getLastReadTime() + "\""); if (rntbdChannelStatistics.getTransitTimeoutCount() > 0) { assertThat(rntbdChannelStatisticsString) .contains("\"transitTimeoutCount\":" + rntbdChannelStatistics.getTransitTimeoutCount()); assertThat(rntbdChannelStatisticsString) .contains("\"transitTimeoutStartingTime\":\"" + rntbdChannelStatistics.getTransitTimeoutStartingTime() + "\""); } else { assertThat(rntbdChannelStatisticsString) .doesNotContain("\"transitTimeoutCount\":" + rntbdChannelStatistics.getTransitTimeoutCount()); assertThat(rntbdChannelStatisticsString) .doesNotContain("\"transitTimeoutStartingTime\":\"" + rntbdChannelStatistics.getTransitTimeoutStartingTime() + "\""); } assertThat(rntbdChannelStatisticsString).contains("\"waitForConnectionInit\":" + rntbdChannelStatistics.isWaitForConnectionInit()); } catch (JsonProcessingException e) { fail("Failed to parse RntbdChannelStatistics"); } } } } private CosmosDiagnostics performDocumentOperation( CosmosAsyncContainer cosmosAsyncContainer, OperationType operationType, TestItem createdItem) { if (operationType == OperationType.Query) { String query = "SELECT * from c"; FeedResponse<TestItem> itemFeedResponse = cosmosAsyncContainer.queryItems(query, TestItem.class).byPage().blockFirst(); return itemFeedResponse.getCosmosDiagnostics(); } if (operationType == OperationType.Read) { return cosmosAsyncContainer .readItem(createdItem.id, new PartitionKey(createdItem.mypk), TestItem.class) .block() .getDiagnostics(); } if (operationType == OperationType.Replace) { return cosmosAsyncContainer .replaceItem(createdItem, createdItem.id, new PartitionKey(createdItem.mypk)) .block() .getDiagnostics(); } if (operationType == OperationType.Create) { return cosmosAsyncContainer.createItem(TestItem.createNewItem()).block().getDiagnostics(); } throw new IllegalArgumentException("The operation type is not supported"); } public static class TestItem { public String id; public String mypk; public TestItem() { } public TestItem(String id, String mypk) { this.id = id; this.mypk = mypk; } public static TestItem createNewItem() { return new TestItem(UUID.randomUUID().toString(), UUID.randomUUID().toString()); } } }
good catch!
public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithAzureCli(request) .doOnNext(token -> LoggingUtil.logTokenSuccess(LOGGER, request)) .doOnError(error -> LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, error)) .onErrorMap(error -> new CredentialUnavailableException("Azure CLI authentication is not available", error)); }
.onErrorMap(error -> new CredentialUnavailableException("Azure CLI authentication is not available", error));
public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithAzureCli(request) .doOnNext(token -> LoggingUtil.logTokenSuccess(LOGGER, request)) .doOnError(error -> LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, error)) .onErrorMap(error -> { if (identityClient.getIdentityClientOptions().isChained()) { return new CredentialUnavailableException(error.getMessage(), error); } else { return error; } }); }
class AzureCliCredential implements TokenCredential { private static final ClientLogger LOGGER = new ClientLogger(AzureCliCredential.class); private final IdentityClient identityClient; private final IdentitySyncClient identitySyncClient; /** * Creates an AzureCliSecretCredential with default identity client options. * @param tenantId the tenant id of the application * @param identityClientOptions the options to configure the identity client */ AzureCliCredential(String tenantId, IdentityClientOptions identityClientOptions) { IdentityClientBuilder builder = new IdentityClientBuilder() .tenantId(tenantId) .identityClientOptions(identityClientOptions); identityClient = builder.build(); identitySyncClient = builder.buildSyncClient(); } @Override @Override public AccessToken getTokenSync(TokenRequestContext request) { try { AccessToken accessToken = identitySyncClient.authenticateWithAzureCli(request); LoggingUtil.logTokenSuccess(LOGGER, request); return accessToken; } catch (Exception e) { LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, e); throw new CredentialUnavailableException("Azure CLI authentication is not available", e); } } }
class AzureCliCredential implements TokenCredential { private static final ClientLogger LOGGER = new ClientLogger(AzureCliCredential.class); private final IdentityClient identityClient; private final IdentitySyncClient identitySyncClient; /** * Creates an AzureCliSecretCredential with default identity client options. * @param tenantId the tenant id of the application * @param identityClientOptions the options to configure the identity client */ AzureCliCredential(String tenantId, IdentityClientOptions identityClientOptions) { IdentityClientBuilder builder = new IdentityClientBuilder() .tenantId(tenantId) .identityClientOptions(identityClientOptions); identityClient = builder.build(); identitySyncClient = builder.buildSyncClient(); } @Override @Override public AccessToken getTokenSync(TokenRequestContext request) { try { AccessToken accessToken = identitySyncClient.authenticateWithAzureCli(request); LoggingUtil.logTokenSuccess(LOGGER, request); return accessToken; } catch (Exception e) { LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, e); if (identityClient.getIdentityClientOptions().isChained()) { throw new CredentialUnavailableException(e.getMessage(), e); } else { throw e; } } } }
These are the configs used in RntbdObjectMapper. Serialization works as expected without filter provider and deserializer settings as well. So I've removed them.
private static ObjectMapper createAndInitializeDurationObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); SimpleFilterProvider filterProvider = new SimpleFilterProvider(); objectMapper.registerModule(new SimpleModule() .addSerializer(Duration.class, ToStringSerializer.instance) .addDeserializer(Duration.class, DurationDeserializer.INSTANCE) .addSerializer(Instant.class, ToStringSerializer.instance)) .setFilterProvider(filterProvider); return objectMapper; }
.setFilterProvider(filterProvider);
private static ObjectMapper createAndInitializeDurationObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new SimpleModule() .addSerializer(Duration.class, ToStringSerializer.instance) .addSerializer(Instant.class, ToStringSerializer.instance)); return objectMapper; }
class Utils { private final static Logger logger = LoggerFactory.getLogger(Utils.class); private static final int JAVA_VERSION = getJavaVersion(); private static final int ONE_KB = 1024; private static final ZoneId GMT_ZONE_ID = ZoneId.of("GMT"); public static final Base64.Encoder Base64Encoder = Base64.getEncoder(); public static final Base64.Decoder Base64Decoder = Base64.getDecoder(); public static final Base64.Encoder Base64UrlEncoder = Base64.getUrlEncoder(); private static final ObjectMapper simpleObjectMapperAllowingDuplicatedProperties = createAndInitializeObjectMapper(true); private static final ObjectMapper simpleObjectMapperDisallowingDuplicatedProperties = createAndInitializeObjectMapper(false); private static final ObjectMapper durationEnabledObjectMapper = createAndInitializeDurationObjectMapper(); private static ObjectMapper simpleObjectMapper = simpleObjectMapperDisallowingDuplicatedProperties; private static final TimeBasedGenerator TIME_BASED_GENERATOR = Generators.timeBasedGenerator(EthernetAddress.constructMulticastAddress()); private static final Pattern SPACE_PATTERN = Pattern.compile("\\s"); private static final DateTimeFormatter RFC_1123_DATE_TIME = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); private static ObjectMapper createAndInitializeObjectMapper(boolean allowDuplicateProperties) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); if (!allowDuplicateProperties) { objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); } objectMapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false); if (JAVA_VERSION != -1 && JAVA_VERSION < 16) { objectMapper.registerModule(new AfterburnerModule()); } objectMapper.registerModule(new JavaTimeModule()); return objectMapper; } private static int getJavaVersion() { int version = -1; try { String completeJavaVersion = System.getProperty("java.version"); String[] versionElements = completeJavaVersion.split("\\."); int versionFirstPart = Integer.parseInt(versionElements[0]); if (versionFirstPart == 1) { version = Integer.parseInt(versionElements[1]); } else { version = versionFirstPart; } return version; } catch (Exception ex) { logger.warn("Error while fetching java version", ex); return version; } } public static byte[] getUTF8BytesOrNull(String str) { if (str == null) { return null; } return str.getBytes(StandardCharsets.UTF_8); } public static byte[] getUTF8Bytes(String str) { return str.getBytes(StandardCharsets.UTF_8); } public static String encodeBase64String(byte[] binaryData) { String encodedString = Base64Encoder.encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static String decodeBase64String(String encodedString) { byte[] decodeString = Base64Decoder.decode(encodedString); return new String(decodeString, StandardCharsets.UTF_8); } public static String decodeAsUTF8String(String inputString) { if (inputString == null || inputString.isEmpty()) { return inputString; } try { return URLDecoder.decode(inputString, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { logger.warn("Error while decoding input string", e); return inputString; } } public static String encodeUrlBase64String(byte[] binaryData) { String encodedString = Base64UrlEncoder.withoutPadding().encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static void configureSimpleObjectMapper(boolean allowDuplicateProperties) { if (allowDuplicateProperties) { Utils.simpleObjectMapper = Utils.simpleObjectMapperAllowingDuplicatedProperties; } else { Utils.simpleObjectMapper = Utils.simpleObjectMapperDisallowingDuplicatedProperties; } } /** * Joins the specified paths by appropriately padding them with '/' * * @param path1 the first path segment to join. * @param path2 the second path segment to join. * @return the concatenated path with '/' */ public static String joinPath(String path1, String path2) { path1 = trimBeginningAndEndingSlashes(path1); String result = "/" + path1 + "/"; if (!StringUtils.isEmpty(path2)) { path2 = trimBeginningAndEndingSlashes(path2); result += path2 + "/"; } return result; } /** * Trims the beginning and ending '/' from the given path * * @param path the path to trim for beginning and ending slashes * @return the path without beginning and ending '/' */ public static String trimBeginningAndEndingSlashes(String path) { if(path == null) { return null; } if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path; } public static String createQuery(Map<String, String> queryParameters) { if (queryParameters == null) return ""; StringBuilder queryString = new StringBuilder(); for (Map.Entry<String, String> nameValuePair : queryParameters.entrySet()) { String key = nameValuePair.getKey(); String value = nameValuePair.getValue(); if (key != null && !key.isEmpty()) { if (queryString.length() > 0) { queryString.append(RuntimeConstants.Separators.Query[1]); } queryString.append(key); if (value != null) { queryString.append(RuntimeConstants.Separators.Query[2]); queryString.append(value); } } } return queryString.toString(); } public static URI setQuery(String urlString, String query) { if (urlString == null) throw new IllegalStateException("urlString parameter can't be null."); query = Utils.removeLeadingQuestionMark(query); try { if (query != null && !query.isEmpty()) { return new URI(Utils.addTrailingSlash(urlString) + RuntimeConstants.Separators.Query[0] + query); } else { return new URI(Utils.addTrailingSlash(urlString)); } } catch (URISyntaxException e) { throw new IllegalStateException("Uri is invalid: ", e); } } /** * Given the full path to a resource, extract the collection path. * * @param resourceFullName the full path to the resource. * @return the path of the collection in which the resource is. */ public static String getCollectionName(String resourceFullName) { if (resourceFullName != null) { resourceFullName = Utils.trimBeginningAndEndingSlashes(resourceFullName); int slashCount = 0; for (int i = 0; i < resourceFullName.length(); i++) { if (resourceFullName.charAt(i) == '/') { slashCount++; if (slashCount == 4) { return resourceFullName.substring(0, i); } } } } return resourceFullName; } public static <T> int getCollectionSize(Collection<T> collection) { if (collection == null) { return 0; } return collection.size(); } public static boolean isCollectionChild(ResourceType type) { return type == ResourceType.Document || type == ResourceType.Attachment || type == ResourceType.Conflict || type == ResourceType.StoredProcedure || type == ResourceType.Trigger || type == ResourceType.UserDefinedFunction; } public static boolean isWriteOperation(OperationType operationType) { return operationType == OperationType.Create || operationType == OperationType.Upsert || operationType == OperationType.Delete || operationType == OperationType.Replace || operationType == OperationType.ExecuteJavaScript || operationType == OperationType.Batch; } private static String addTrailingSlash(String path) { if (path == null || path.isEmpty()) path = new String(RuntimeConstants.Separators.Url); else if (path.charAt(path.length() - 1) != RuntimeConstants.Separators.Url[0]) path = path + RuntimeConstants.Separators.Url[0]; return path; } private static String removeLeadingQuestionMark(String path) { if (path == null || path.isEmpty()) return path; if (path.charAt(0) == RuntimeConstants.Separators.Query[0]) return path.substring(1); return path; } public static boolean isValidConsistency(ConsistencyLevel backendConsistency, ConsistencyLevel desiredConsistency) { switch (backendConsistency) { case STRONG: return desiredConsistency == ConsistencyLevel.STRONG || desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case BOUNDED_STALENESS: return desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case SESSION: case EVENTUAL: case CONSISTENT_PREFIX: return desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; default: throw new IllegalArgumentException("backendConsistency"); } } public static String getUserAgent() { return getUserAgent(HttpConstants.Versions.SDK_NAME, HttpConstants.Versions.getSdkVersion()); } public static String getUserAgent(String sdkName, String sdkVersion) { String osName = System.getProperty("os.name"); if (osName == null) { osName = "Unknown"; } osName = SPACE_PATTERN.matcher(osName).replaceAll(""); return String.format("%s%s/%s %s/%s JRE/%s", UserAgentContainer.AZSDK_USERAGENT_PREFIX, sdkName, sdkVersion, osName, System.getProperty("os.version"), System.getProperty("java.version") ); } public static ObjectMapper getSimpleObjectMapper() { return Utils.simpleObjectMapper; } public static ObjectMapper getDurationEnabledObjectMapper() { return Utils.durationEnabledObjectMapper; } /** * Returns Current Time in RFC 1123 format, e.g, * Fri, 01 Dec 2017 19:22:30 GMT. * * @return an instance of STRING */ public static String nowAsRFC1123() { ZonedDateTime now = ZonedDateTime.now(GMT_ZONE_ID); return Utils.RFC_1123_DATE_TIME.format(now); } public static UUID randomUUID() { return TIME_BASED_GENERATOR.generate(); } public static String instantAsUTCRFC1123(Instant instant){ return Utils.RFC_1123_DATE_TIME.format(instant.atZone(GMT_ZONE_ID)); } public static int getValueOrDefault(Integer val, int defaultValue) { return val != null ? val : defaultValue; } public static void checkStateOrThrow(boolean value, String argumentName, String message) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, message); if (t != null) { throw t; } } public static void checkNotNullOrThrow(Object val, String argumentName, String message) throws NullPointerException { NullPointerException t = checkNotNullOrReturnException(val, argumentName, message); if (t != null) { throw t; } } public static void checkStateOrThrow(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, argumentName, messageTemplateParams); if (t != null) { throw t; } } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String message) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, message)); } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } private static NullPointerException checkNotNullOrReturnException(Object val, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (val != null) { return null; } return new NullPointerException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } @SuppressWarnings("unchecked") public static <O, I> O as(I i, Class<O> klass) { if (i == null) { return null; } if (klass.isInstance(i)) { return (O) i; } else { return null; } } @SuppressWarnings("unchecked") public static <V> List<V> immutableListOf() { return Collections.EMPTY_LIST; } public static <K, V> Map<K, V>immutableMapOf(K k1, V v1) { Map<K, V> map = new HashMap<>(); map.put(k1, v1); map = Collections.unmodifiableMap(map); return map; } public static <V> V firstOrDefault(List<V> list) { return list.size() > 0? list.get(0) : null ; } public static class ValueHolder<V> { public ValueHolder() { } public ValueHolder(V v) { this.v = v; } public V v; public static <T> ValueHolder<T> initialize(T v) { return new ValueHolder<>(v); } } public static <K, V> boolean tryGetValue(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.get(key); return holder.v != null; } public static <K, V> boolean tryRemove(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.remove(key); return holder.v != null; } public static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) { if (StringUtils.isEmpty(itemResponseBodyAsString)) { return null; } try { return getSimpleObjectMapper().readValue(itemResponseBodyAsString, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse string [%s] to POJO.", itemResponseBodyAsString), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType) { if (Utils.isEmpty(item)) { return null; } try { return getSimpleObjectMapper().readValue(item, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse byte-array %s to POJO.", Arrays.toString(item)), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType, ItemDeserializer itemDeserializer) { if (Utils.isEmpty(item)) { return null; } if (itemDeserializer == null) { return Utils.parse(item, itemClassType); } return itemDeserializer.parseFrom(itemClassType, item); } public static ByteBuffer serializeJsonToByteBuffer(ObjectMapper objectMapper, Object object) { try { ByteBufferOutputStream byteBufferOutputStream = new ByteBufferOutputStream(ONE_KB); objectMapper.writeValue(byteBufferOutputStream, object); return byteBufferOutputStream.asByteBuffer(); } catch (IOException e) { throw new IllegalArgumentException("Failed to serialize the object into json", e); } } public static boolean isEmpty(byte[] bytes) { return bytes == null || bytes.length == 0; } public static String utf8StringFromOrNull(byte[] bytes) { if (bytes == null) { return null; } return new String(bytes, StandardCharsets.UTF_8); } public static void setContinuationTokenAndMaxItemCount(CosmosPagedFluxOptions pagedFluxOptions, CosmosQueryRequestOptions cosmosQueryRequestOptions) { if (pagedFluxOptions == null) { return; } if (pagedFluxOptions.getRequestContinuation() != null) { ModelBridgeInternal.setQueryRequestOptionsContinuationToken(cosmosQueryRequestOptions, pagedFluxOptions.getRequestContinuation()); } if (pagedFluxOptions.getMaxItemCount() != null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions.getMaxItemCount()); } else { ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .applyMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions); if (pagedFluxOptions.getMaxItemCount() == null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount( cosmosQueryRequestOptions, Constants.Properties.DEFAULT_MAX_PAGE_SIZE); pagedFluxOptions.setMaxItemCount(Constants.Properties.DEFAULT_MAX_PAGE_SIZE); } } } public static CosmosChangeFeedRequestOptions getEffectiveCosmosChangeFeedRequestOptions( CosmosPagedFluxOptions pagedFluxOptions, CosmosChangeFeedRequestOptions cosmosChangeFeedRequestRequestOptions) { checkNotNull( cosmosChangeFeedRequestRequestOptions, "Argument 'cosmosChangeFeedRequestRequestOptions' must not be null"); return ModelBridgeInternal .getEffectiveChangeFeedRequestOptions( cosmosChangeFeedRequestRequestOptions, pagedFluxOptions); } static String escapeNonAscii(String partitionKeyJson) { StringBuilder sb = null; for (int i = 0; i < partitionKeyJson.length(); i++) { int val = partitionKeyJson.charAt(i); if (val > 127) { if (sb == null) { sb = new StringBuilder(partitionKeyJson.length()); sb.append(partitionKeyJson, 0, i); } sb.append("\\u").append(String.format("%04X", val)); } else { if (sb != null) { sb.append(partitionKeyJson.charAt(i)); } } } if (sb == null) { return partitionKeyJson; } else { return sb.toString(); } } public static byte[] toByteArray(ByteBuf buf) { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); return bytes; } public static String toJson(ObjectMapper mapper, ObjectNode object) { try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert JSON to STRING", e); } } public static long getMaxIntegratedCacheStalenessInMillis(DedicatedGatewayRequestOptions dedicatedGatewayRequestOptions) { Duration maxIntegratedCacheStaleness = dedicatedGatewayRequestOptions.getMaxIntegratedCacheStaleness(); if (maxIntegratedCacheStaleness.toNanos() > 0 && maxIntegratedCacheStaleness.toMillis() <= 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness granularity is milliseconds"); } if (maxIntegratedCacheStaleness.toMillis() < 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness duration cannot be negative"); } return maxIntegratedCacheStaleness.toMillis(); } }
class Utils { private final static Logger logger = LoggerFactory.getLogger(Utils.class); private static final int JAVA_VERSION = getJavaVersion(); private static final int ONE_KB = 1024; private static final ZoneId GMT_ZONE_ID = ZoneId.of("GMT"); public static final Base64.Encoder Base64Encoder = Base64.getEncoder(); public static final Base64.Decoder Base64Decoder = Base64.getDecoder(); public static final Base64.Encoder Base64UrlEncoder = Base64.getUrlEncoder(); private static final ObjectMapper simpleObjectMapperAllowingDuplicatedProperties = createAndInitializeObjectMapper(true); private static final ObjectMapper simpleObjectMapperDisallowingDuplicatedProperties = createAndInitializeObjectMapper(false); private static final ObjectMapper durationEnabledObjectMapper = createAndInitializeDurationObjectMapper(); private static ObjectMapper simpleObjectMapper = simpleObjectMapperDisallowingDuplicatedProperties; private static final TimeBasedGenerator TIME_BASED_GENERATOR = Generators.timeBasedGenerator(EthernetAddress.constructMulticastAddress()); private static final Pattern SPACE_PATTERN = Pattern.compile("\\s"); private static final DateTimeFormatter RFC_1123_DATE_TIME = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); private static ObjectMapper createAndInitializeObjectMapper(boolean allowDuplicateProperties) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); if (!allowDuplicateProperties) { objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); } objectMapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false); if (JAVA_VERSION != -1 && JAVA_VERSION < 16) { objectMapper.registerModule(new AfterburnerModule()); } objectMapper.registerModule(new JavaTimeModule()); return objectMapper; } private static int getJavaVersion() { int version = -1; try { String completeJavaVersion = System.getProperty("java.version"); String[] versionElements = completeJavaVersion.split("\\."); int versionFirstPart = Integer.parseInt(versionElements[0]); if (versionFirstPart == 1) { version = Integer.parseInt(versionElements[1]); } else { version = versionFirstPart; } return version; } catch (Exception ex) { logger.warn("Error while fetching java version", ex); return version; } } public static byte[] getUTF8BytesOrNull(String str) { if (str == null) { return null; } return str.getBytes(StandardCharsets.UTF_8); } public static byte[] getUTF8Bytes(String str) { return str.getBytes(StandardCharsets.UTF_8); } public static String encodeBase64String(byte[] binaryData) { String encodedString = Base64Encoder.encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static String decodeBase64String(String encodedString) { byte[] decodeString = Base64Decoder.decode(encodedString); return new String(decodeString, StandardCharsets.UTF_8); } public static String decodeAsUTF8String(String inputString) { if (inputString == null || inputString.isEmpty()) { return inputString; } try { return URLDecoder.decode(inputString, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { logger.warn("Error while decoding input string", e); return inputString; } } public static String encodeUrlBase64String(byte[] binaryData) { String encodedString = Base64UrlEncoder.withoutPadding().encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static void configureSimpleObjectMapper(boolean allowDuplicateProperties) { if (allowDuplicateProperties) { Utils.simpleObjectMapper = Utils.simpleObjectMapperAllowingDuplicatedProperties; } else { Utils.simpleObjectMapper = Utils.simpleObjectMapperDisallowingDuplicatedProperties; } } /** * Joins the specified paths by appropriately padding them with '/' * * @param path1 the first path segment to join. * @param path2 the second path segment to join. * @return the concatenated path with '/' */ public static String joinPath(String path1, String path2) { path1 = trimBeginningAndEndingSlashes(path1); String result = "/" + path1 + "/"; if (!StringUtils.isEmpty(path2)) { path2 = trimBeginningAndEndingSlashes(path2); result += path2 + "/"; } return result; } /** * Trims the beginning and ending '/' from the given path * * @param path the path to trim for beginning and ending slashes * @return the path without beginning and ending '/' */ public static String trimBeginningAndEndingSlashes(String path) { if(path == null) { return null; } if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path; } public static String createQuery(Map<String, String> queryParameters) { if (queryParameters == null) return ""; StringBuilder queryString = new StringBuilder(); for (Map.Entry<String, String> nameValuePair : queryParameters.entrySet()) { String key = nameValuePair.getKey(); String value = nameValuePair.getValue(); if (key != null && !key.isEmpty()) { if (queryString.length() > 0) { queryString.append(RuntimeConstants.Separators.Query[1]); } queryString.append(key); if (value != null) { queryString.append(RuntimeConstants.Separators.Query[2]); queryString.append(value); } } } return queryString.toString(); } public static URI setQuery(String urlString, String query) { if (urlString == null) throw new IllegalStateException("urlString parameter can't be null."); query = Utils.removeLeadingQuestionMark(query); try { if (query != null && !query.isEmpty()) { return new URI(Utils.addTrailingSlash(urlString) + RuntimeConstants.Separators.Query[0] + query); } else { return new URI(Utils.addTrailingSlash(urlString)); } } catch (URISyntaxException e) { throw new IllegalStateException("Uri is invalid: ", e); } } /** * Given the full path to a resource, extract the collection path. * * @param resourceFullName the full path to the resource. * @return the path of the collection in which the resource is. */ public static String getCollectionName(String resourceFullName) { if (resourceFullName != null) { resourceFullName = Utils.trimBeginningAndEndingSlashes(resourceFullName); int slashCount = 0; for (int i = 0; i < resourceFullName.length(); i++) { if (resourceFullName.charAt(i) == '/') { slashCount++; if (slashCount == 4) { return resourceFullName.substring(0, i); } } } } return resourceFullName; } public static <T> int getCollectionSize(Collection<T> collection) { if (collection == null) { return 0; } return collection.size(); } public static boolean isCollectionChild(ResourceType type) { return type == ResourceType.Document || type == ResourceType.Attachment || type == ResourceType.Conflict || type == ResourceType.StoredProcedure || type == ResourceType.Trigger || type == ResourceType.UserDefinedFunction; } public static boolean isWriteOperation(OperationType operationType) { return operationType == OperationType.Create || operationType == OperationType.Upsert || operationType == OperationType.Delete || operationType == OperationType.Replace || operationType == OperationType.ExecuteJavaScript || operationType == OperationType.Batch; } private static String addTrailingSlash(String path) { if (path == null || path.isEmpty()) path = new String(RuntimeConstants.Separators.Url); else if (path.charAt(path.length() - 1) != RuntimeConstants.Separators.Url[0]) path = path + RuntimeConstants.Separators.Url[0]; return path; } private static String removeLeadingQuestionMark(String path) { if (path == null || path.isEmpty()) return path; if (path.charAt(0) == RuntimeConstants.Separators.Query[0]) return path.substring(1); return path; } public static boolean isValidConsistency(ConsistencyLevel backendConsistency, ConsistencyLevel desiredConsistency) { switch (backendConsistency) { case STRONG: return desiredConsistency == ConsistencyLevel.STRONG || desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case BOUNDED_STALENESS: return desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case SESSION: case EVENTUAL: case CONSISTENT_PREFIX: return desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; default: throw new IllegalArgumentException("backendConsistency"); } } public static String getUserAgent() { return getUserAgent(HttpConstants.Versions.SDK_NAME, HttpConstants.Versions.getSdkVersion()); } public static String getUserAgent(String sdkName, String sdkVersion) { String osName = System.getProperty("os.name"); if (osName == null) { osName = "Unknown"; } osName = SPACE_PATTERN.matcher(osName).replaceAll(""); return String.format("%s%s/%s %s/%s JRE/%s", UserAgentContainer.AZSDK_USERAGENT_PREFIX, sdkName, sdkVersion, osName, System.getProperty("os.version"), System.getProperty("java.version") ); } public static ObjectMapper getSimpleObjectMapper() { return Utils.simpleObjectMapper; } public static ObjectMapper getDurationEnabledObjectMapper() { return durationEnabledObjectMapper; } /** * Returns Current Time in RFC 1123 format, e.g, * Fri, 01 Dec 2017 19:22:30 GMT. * * @return an instance of STRING */ public static String nowAsRFC1123() { ZonedDateTime now = ZonedDateTime.now(GMT_ZONE_ID); return Utils.RFC_1123_DATE_TIME.format(now); } public static UUID randomUUID() { return TIME_BASED_GENERATOR.generate(); } public static String instantAsUTCRFC1123(Instant instant){ return Utils.RFC_1123_DATE_TIME.format(instant.atZone(GMT_ZONE_ID)); } public static int getValueOrDefault(Integer val, int defaultValue) { return val != null ? val : defaultValue; } public static void checkStateOrThrow(boolean value, String argumentName, String message) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, message); if (t != null) { throw t; } } public static void checkNotNullOrThrow(Object val, String argumentName, String message) throws NullPointerException { NullPointerException t = checkNotNullOrReturnException(val, argumentName, message); if (t != null) { throw t; } } public static void checkStateOrThrow(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, argumentName, messageTemplateParams); if (t != null) { throw t; } } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String message) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, message)); } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } private static NullPointerException checkNotNullOrReturnException(Object val, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (val != null) { return null; } return new NullPointerException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } @SuppressWarnings("unchecked") public static <O, I> O as(I i, Class<O> klass) { if (i == null) { return null; } if (klass.isInstance(i)) { return (O) i; } else { return null; } } @SuppressWarnings("unchecked") public static <V> List<V> immutableListOf() { return Collections.EMPTY_LIST; } public static <K, V> Map<K, V>immutableMapOf(K k1, V v1) { Map<K, V> map = new HashMap<>(); map.put(k1, v1); map = Collections.unmodifiableMap(map); return map; } public static <V> V firstOrDefault(List<V> list) { return list.size() > 0? list.get(0) : null ; } public static class ValueHolder<V> { public ValueHolder() { } public ValueHolder(V v) { this.v = v; } public V v; public static <T> ValueHolder<T> initialize(T v) { return new ValueHolder<>(v); } } public static <K, V> boolean tryGetValue(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.get(key); return holder.v != null; } public static <K, V> boolean tryRemove(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.remove(key); return holder.v != null; } public static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) { if (StringUtils.isEmpty(itemResponseBodyAsString)) { return null; } try { return getSimpleObjectMapper().readValue(itemResponseBodyAsString, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse string [%s] to POJO.", itemResponseBodyAsString), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType) { if (Utils.isEmpty(item)) { return null; } try { return getSimpleObjectMapper().readValue(item, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse byte-array %s to POJO.", Arrays.toString(item)), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType, ItemDeserializer itemDeserializer) { if (Utils.isEmpty(item)) { return null; } if (itemDeserializer == null) { return Utils.parse(item, itemClassType); } return itemDeserializer.parseFrom(itemClassType, item); } public static ByteBuffer serializeJsonToByteBuffer(ObjectMapper objectMapper, Object object) { try { ByteBufferOutputStream byteBufferOutputStream = new ByteBufferOutputStream(ONE_KB); objectMapper.writeValue(byteBufferOutputStream, object); return byteBufferOutputStream.asByteBuffer(); } catch (IOException e) { throw new IllegalArgumentException("Failed to serialize the object into json", e); } } public static boolean isEmpty(byte[] bytes) { return bytes == null || bytes.length == 0; } public static String utf8StringFromOrNull(byte[] bytes) { if (bytes == null) { return null; } return new String(bytes, StandardCharsets.UTF_8); } public static void setContinuationTokenAndMaxItemCount(CosmosPagedFluxOptions pagedFluxOptions, CosmosQueryRequestOptions cosmosQueryRequestOptions) { if (pagedFluxOptions == null) { return; } if (pagedFluxOptions.getRequestContinuation() != null) { ModelBridgeInternal.setQueryRequestOptionsContinuationToken(cosmosQueryRequestOptions, pagedFluxOptions.getRequestContinuation()); } if (pagedFluxOptions.getMaxItemCount() != null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions.getMaxItemCount()); } else { ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .applyMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions); if (pagedFluxOptions.getMaxItemCount() == null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount( cosmosQueryRequestOptions, Constants.Properties.DEFAULT_MAX_PAGE_SIZE); pagedFluxOptions.setMaxItemCount(Constants.Properties.DEFAULT_MAX_PAGE_SIZE); } } } public static CosmosChangeFeedRequestOptions getEffectiveCosmosChangeFeedRequestOptions( CosmosPagedFluxOptions pagedFluxOptions, CosmosChangeFeedRequestOptions cosmosChangeFeedRequestRequestOptions) { checkNotNull( cosmosChangeFeedRequestRequestOptions, "Argument 'cosmosChangeFeedRequestRequestOptions' must not be null"); return ModelBridgeInternal .getEffectiveChangeFeedRequestOptions( cosmosChangeFeedRequestRequestOptions, pagedFluxOptions); } static String escapeNonAscii(String partitionKeyJson) { StringBuilder sb = null; for (int i = 0; i < partitionKeyJson.length(); i++) { int val = partitionKeyJson.charAt(i); if (val > 127) { if (sb == null) { sb = new StringBuilder(partitionKeyJson.length()); sb.append(partitionKeyJson, 0, i); } sb.append("\\u").append(String.format("%04X", val)); } else { if (sb != null) { sb.append(partitionKeyJson.charAt(i)); } } } if (sb == null) { return partitionKeyJson; } else { return sb.toString(); } } public static byte[] toByteArray(ByteBuf buf) { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); return bytes; } public static String toJson(ObjectMapper mapper, ObjectNode object) { try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert JSON to STRING", e); } } public static long getMaxIntegratedCacheStalenessInMillis(DedicatedGatewayRequestOptions dedicatedGatewayRequestOptions) { Duration maxIntegratedCacheStaleness = dedicatedGatewayRequestOptions.getMaxIntegratedCacheStaleness(); if (maxIntegratedCacheStaleness.toNanos() > 0 && maxIntegratedCacheStaleness.toMillis() <= 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness granularity is milliseconds"); } if (maxIntegratedCacheStaleness.toMillis() < 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness duration cannot be negative"); } return maxIntegratedCacheStaleness.toMillis(); } }
Yes we do have a durationInMilliSecs field. Added that as well here for verification
public void gatewayDiagnosticsOnException() throws Exception { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = null; try { createResponse = this.containerGateway.createItem(internalObjectNode); CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey")); CosmosItemResponse<InternalObjectNode> readResponse = this.containerGateway.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey("wrongPartitionKey"), InternalObjectNode.class); fail("request should fail as partition key is wrong"); } catch (CosmosException exception) { System.out.println(exception.getDiagnostics()); isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND); assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).contains("gatewayStatisticsList"); assertThat(diagnostics).contains("\"statusCode\":404"); assertThat(diagnostics).contains("\"operationType\":\"Read\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).contains("\"exceptionMessage\":\"Message: {\\\"Errors\\\":[\\\"Resource Not Found. Learn more: https:\\\\/\\\\/aka.ms\\\\/cosmosdb-tsg-not-found\\\""); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(createResponse.getDiagnostics().getContactedRegionNames()).isNotNull(); validateRegionContacted(createResponse.getDiagnostics(), this.containerGateway.asyncContainer.getDatabase().getClient()); assertThat(createResponse.getDiagnostics().getRegionsContacted()).isNotEmpty(); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); validateTransportRequestTimelineGateway(diagnostics); isValidJSON(diagnostics); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void systemDiagnosticsForSystemStateInformation() { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = this.containerGateway.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("systemInformation"); assertThat(diagnostics).contains("usedMemory"); assertThat(diagnostics).contains("availableMemory"); assertThat(diagnostics).contains("systemCpuLoad"); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnostics() throws Exception { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = containerDirect.createItem(internalObjectNode); validateDirectModeDiagnosticsOnSuccess(createResponse.getDiagnostics(), directClient, this.directClientUserAgent); try { containerDirect.createItem(internalObjectNode); fail("expected 409"); } catch (CosmosException e) { validateDirectModeDiagnosticsOnException(e, this.directClientUserAgent); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void requestSessionTokenDiagnostics() { CosmosClient testSessionTokenClient = null; try { testSessionTokenClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .consistencyLevel(ConsistencyLevel.SESSION) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer cosmosContainer = testSessionTokenClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"requestSessionToken\":null"); String sessionToken = createResponse.getSessionToken(); CosmosItemResponse<InternalObjectNode> readResponse = cosmosContainer.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey(BridgeInternal.getProperties(createResponse).getId()), InternalObjectNode.class); diagnostics = readResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"requestSessionToken\":\"%s\"", sessionToken)); CosmosBatch batch = CosmosBatch.createCosmosBatch(new PartitionKey( BridgeInternal.getProperties(createResponse).getId())); internalObjectNode = getInternalObjectNode(); batch.createItemOperation(internalObjectNode); CosmosBatchResponse batchResponse = cosmosContainer.executeCosmosBatch(batch, new CosmosBatchRequestOptions().setSessionToken(readResponse.getSessionToken())); diagnostics = batchResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"requestSessionToken\":\"%s\"", readResponse.getSessionToken())); } finally { if (testSessionTokenClient != null) { testSessionTokenClient.close(); } } } @Test(groups = {"simple"}) public void databaseAccountToClients() { CosmosClient testClient = null; try { testClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer cosmosContainer = testClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"clientEndpoints\"" + ":{\"%s\"", TestConfigurations.HOST)); int clientsIndex = diagnostics.indexOf("\"clientEndpoints\":"); String[] substrings = diagnostics.substring(clientsIndex, clientsIndex + 120) .split("}")[0].split(":"); String intString = substrings[substrings.length-1]; int intValue = Integer.parseInt(intString); CosmosClient testClient2 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); internalObjectNode = getInternalObjectNode(); createResponse = cosmosContainer.createItem(internalObjectNode); diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"clientEndpoints\"" + ":{\"%s\"", TestConfigurations.HOST)); clientsIndex = diagnostics.indexOf("\"clientEndpoints\":"); substrings = diagnostics.substring(clientsIndex, clientsIndex + 120) .split("}")[0].split(":"); intString = substrings[substrings.length-1]; assertThat(Integer.parseInt(intString)).isEqualTo(intValue+1); testClient2.close(); } finally { if (testClient != null) { testClient.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryPlanDiagnostics() throws JsonProcessingException { List<String> itemIdList = new ArrayList<>(); for(int i = 0; i< 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = containerDirect.createItem(internalObjectNode); if(i%20 == 0) { itemIdList.add(internalObjectNode.getId()); } } String queryDiagnostics = null; List<String> queryList = new ArrayList<>(); queryList.add("Select * from c"); StringBuilder queryBuilder = new StringBuilder("SELECT * from c where c.mypk in ("); for(int i = 0 ; i < itemIdList.size(); i++){ queryBuilder.append("'").append(itemIdList.get(i)).append("'"); if(i < (itemIdList.size()-1)) { queryBuilder.append(","); } else { queryBuilder.append(")"); } } queryList.add(queryBuilder.toString()); queryList.add("Select * from c where c.id = 'wrongId'"); for(String query : queryList) { int feedResponseCounter = 0; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setQueryMetricsEnabled(true); Iterator<FeedResponse<InternalObjectNode>> iterator = containerDirect.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); if (feedResponseCounter == 0) { assertThat(queryDiagnostics).contains("queryPlanDiagnosticsContext"); assertThat(queryDiagnostics).contains("startTimeUTC"); assertThat(queryDiagnostics).contains("endTimeUTC"); String requestTimeLine = OBJECT_MAPPER.writeValueAsString(feedResponse.getCosmosDiagnostics().getFeedResponseDiagnostics().getQueryPlanDiagnosticsContext().getRequestTimeline()); assertThat(requestTimeLine).contains("connectionConfigured"); assertThat(requestTimeLine).contains("requestSent"); assertThat(requestTimeLine).contains("transitTime"); assertThat(requestTimeLine).contains("received"); } else { assertThat(queryDiagnostics).contains("\"queryPlanDiagnosticsContext\":null"); } feedResponseCounter++; } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readManyDiagnostics() { String pkValue = UUID.randomUUID().toString(); PartitionKey partitionKey = new PartitionKey(pkValue); List<CosmosItemIdentity> itemIdList = new ArrayList<>(); for(int i = 0; i< 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(pkValue); CosmosItemResponse<InternalObjectNode> createResponse = containerDirect.createItem(internalObjectNode); if(i%20 == 0) { itemIdList.add(new CosmosItemIdentity(partitionKey, internalObjectNode.getId())); } } FeedResponse<InternalObjectNode> response = containerDirect.readMany(itemIdList, InternalObjectNode.class); FeedResponseDiagnostics diagnostics = response.getCosmosDiagnostics().getFeedResponseDiagnostics(); assertThat(diagnostics.getClientSideRequestStatistics().size()).isEqualTo(1); assertThat(diagnostics.getQueryMetricsMap().values().iterator().next().getRetrievedDocumentCount()).isEqualTo(itemIdList.size()); String cosmosDiagnosticsString = response.getCosmosDiagnostics().toString(); assertThat(cosmosDiagnosticsString).contains("\"userAgent\":\"" + this.directClientUserAgent + "\""); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryMetricsWithIndexMetrics() { List<String> itemIdList = new ArrayList<>(); for(int i = 0; i< 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = containerDirect.createItem(internalObjectNode); if(i%20 == 0) { itemIdList.add(internalObjectNode.getId()); } } String queryDiagnostics = null; List<String> queryList = new ArrayList<>(); StringBuilder queryBuilder = new StringBuilder("SELECT * from c where c.mypk in ("); for(int i = 0 ; i < itemIdList.size(); i++){ queryBuilder.append("'").append(itemIdList.get(i)).append("'"); if(i < (itemIdList.size()-1)) { queryBuilder.append(","); } else { queryBuilder.append(")"); } } queryList.add(queryBuilder.toString()); for (String query : queryList) { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setQueryMetricsEnabled(true); options.setIndexMetricsEnabled(true); Iterator<FeedResponse<InternalObjectNode>> iterator = containerDirect.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); logger.info("This is query diagnostics {}", queryDiagnostics); if (feedResponse.getResponseHeaders().containsKey(HttpConstants.HttpHeaders.INDEX_UTILIZATION)) { assertThat(feedResponse.getResponseHeaders().get(HttpConstants.HttpHeaders.INDEX_UTILIZATION)).isNotNull(); assertThat(createFromJSONString(Utils.decodeBase64String(feedResponse.getResponseHeaders().get(HttpConstants.HttpHeaders.INDEX_UTILIZATION))).getUtilizedSingleIndexes()).isNotNull(); } } } } @Test(groups = {"simple"}, dataProvider = "query", timeOut = TIMEOUT) public void queryMetrics(String query, Boolean qmEnabled) { CosmosContainer directContainer = this.directClient.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()) .getContainer(this.cosmosAsyncContainer.getId()); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); if (qmEnabled != null) { options.setQueryMetricsEnabled(qmEnabled); } boolean qroupByFirstResponse = true; Iterator<FeedResponse<InternalObjectNode>> iterator = directContainer.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); assertThat(iterator.hasNext()).isTrue(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); assertThat(feedResponse.getResults().size()).isEqualTo(0); if (!query.contains("group by") || qroupByFirstResponse) { validateQueryDiagnostics(queryDiagnostics, qmEnabled, true); validateDirectModeQueryDiagnostics(queryDiagnostics, this.directClientUserAgent); if (query.contains("group by")) { qroupByFirstResponse = false; } } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryDiagnosticsOnOrderBy() { String containerId = "testcontainer"; cosmosAsyncDatabase.createContainer(containerId, "/mypk", ThroughputProperties.createManualThroughput(40000)).block(); CosmosAsyncContainer testcontainer = cosmosAsyncDatabase.getContainer(containerId); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setConsistencyLevel(ConsistencyLevel.EVENTUAL); testcontainer.createItem(getInternalObjectNode()).block(); options.setMaxDegreeOfParallelism(-1); String query = "SELECT * from c ORDER BY c._ts DESC"; CosmosPagedFlux<InternalObjectNode> cosmosPagedFlux = testcontainer.queryItems(query, options, InternalObjectNode.class); Set<String> partitionKeyRangeIds = new HashSet<>(); Set<String> pkRids = new HashSet<>(); cosmosPagedFlux.byPage().flatMap(feedResponse -> { String cosmosDiagnosticsString = feedResponse.getCosmosDiagnostics().toString(); Pattern pattern = Pattern.compile("(\"partitionKeyRangeId\":\")(\\d)"); Matcher matcher = pattern.matcher(cosmosDiagnosticsString); while (matcher.find()) { String group = matcher.group(2); partitionKeyRangeIds.add(group); } pattern = Pattern.compile("(pkrId:)(\\d)"); matcher = pattern.matcher(cosmosDiagnosticsString); while (matcher.find()) { String group = matcher.group(2); pkRids.add(group); } return Flux.just(feedResponse); }).blockLast(); assertThat(pkRids).isNotEmpty(); assertThat(pkRids).isEqualTo(partitionKeyRangeIds); deleteCollection(testcontainer); } @Test(groups = {"simple"}, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) public void directDiagnosticsOnCancelledOperation(OperationType operationType) { CosmosAsyncClient client = null; FaultInjectionRule faultInjectionRule = null; try { client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(TestConfigurations.HOST) .endToEndOperationLatencyPolicyConfig( new CosmosEndToEndOperationLatencyPolicyConfigBuilder(Duration.ofSeconds(1)).build() ).buildAsyncClient(); CosmosAsyncContainer container = client.getDatabase(containerDirect.asyncContainer.getDatabase().getId()).getContainer(containerDirect.getId()); TestItem testItem = TestItem.createNewItem(); container.createItem(testItem).block(); faultInjectionRule = new FaultInjectionRuleBuilder("responseDelay") .condition(new FaultInjectionConditionBuilder().build()) .result( FaultInjectionResultBuilders.getResultBuilder(FaultInjectionServerErrorType.RESPONSE_DELAY) .delay(Duration.ofSeconds(2)) .build() ) .build(); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(faultInjectionRule)).block(); this.performDocumentOperation(container, operationType, testItem); fail("expected OperationCancelledException"); } catch (CosmosException e) { assertThat(e).isInstanceOf(OperationCancelledException.class); String cosmosDiagnosticsString = e.getDiagnostics().toString(); assertThat(cosmosDiagnosticsString).contains("\"statusCode\":408"); assertThat(cosmosDiagnosticsString).contains("\"subStatusCode\":20008"); } finally { if (faultInjectionRule != null) { faultInjectionRule.disable(); } safeClose(client); } } @Test(groups = {"simple"}, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) public void directDiagnostics_WithFaultInjection(OperationType operationType) { CosmosAsyncClient client = null; FaultInjectionRule faultInjectionRule = null; try { client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(TestConfigurations.HOST) .buildAsyncClient(); CosmosAsyncContainer container = client.getDatabase(containerDirect.asyncContainer.getDatabase().getId()).getContainer(containerDirect.getId()); TestItem testItem = TestItem.createNewItem(); container.createItem(testItem).block(); faultInjectionRule = new FaultInjectionRuleBuilder("serverResponseError") .condition(new FaultInjectionConditionBuilder().build()) .result( FaultInjectionResultBuilders.getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .build(); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(faultInjectionRule)).block(); CosmosDiagnostics cosmosDiagnostics = this.performDocumentOperation(container, operationType, testItem); assertThat(cosmosDiagnostics).isNotNull(); String diagnosticsString = cosmosDiagnostics.toString(); assertThat(diagnosticsString).contains("\"statusCode\":410"); assertThat(diagnosticsString).contains("\"subStatusCode\":21005"); assertThat(diagnosticsString).doesNotContain("\"statusCode\":408"); assertThat(diagnosticsString).doesNotContain("\"subStatusCode\":20008"); } catch (CosmosException e) { fail("Request should succeeded but failed with " + e.getMessage()); } finally { if (faultInjectionRule != null) { faultInjectionRule.disable(); } safeClose(client); } } private void validateDirectModeDiagnosticsOnSuccess( CosmosDiagnostics cosmosDiagnostics, CosmosClient testDirectClient, String userAgent) throws Exception { String diagnostics = cosmosDiagnostics.toString(); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("supplementalResponseStatisticsList"); assertThat(diagnostics).contains("gatewayStatisticsList"); assertThat(diagnostics).contains("addressResolutionStatistics"); assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\""); assertThat(diagnostics).contains("\"metaDataName\":\"PARTITION_KEY_RANGE_LOOK_UP\""); assertThat(diagnostics).contains("\"metaDataName\":\"SERVER_ADDRESS_LOOKUP\""); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + userAgent + "\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"backendLatencyInMs\""); assertThat(diagnostics).contains("\"retryAfterInMs\""); assertThat(diagnostics).contains("\"channelStatistics\""); assertThat(cosmosDiagnostics.getContactedRegionNames()).isNotEmpty(); assertThat(cosmosDiagnostics.getDuration()).isNotNull(); validateTransportRequestTimelineDirect(diagnostics); validateRegionContacted(cosmosDiagnostics, testDirectClient.asyncClient()); validateChannelStatistics(cosmosDiagnostics); isValidJSON(diagnostics); } private void validateDirectModeDiagnosticsOnException(CosmosException cosmosException, String userAgent) { CosmosDiagnostics cosmosDiagnostics = cosmosException.getDiagnostics(); String diagnosticsString = cosmosDiagnostics.toString(); assertThat(diagnosticsString).contains("\"backendLatencyInMs\""); assertThat(diagnosticsString).contains("\"userAgent\":\"" + userAgent + "\""); assertThat(diagnosticsString).contains("\"retryAfterInMs\""); assertThat(diagnosticsString).contains("\"exceptionMessage\":\"[\\\"Resource with specified id or name already exists.\\\"]\""); assertThat(diagnosticsString).contains("\"exceptionResponseHeaders\""); assertThat(diagnosticsString).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); validateTransportRequestTimelineDirect(diagnosticsString); validateChannelStatistics(cosmosDiagnostics); if (!(cosmosException instanceof OperationCancelledException)) { assertThat(diagnosticsString).doesNotContain("\"statusCode\":408"); assertThat(diagnosticsString).doesNotContain("\"subStatusCode\":20008"); } } private void validateDirectModeQueryDiagnostics(String diagnostics, String userAgent) { assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("supplementalResponseStatisticsList"); assertThat(diagnostics).contains("responseStatisticsList"); assertThat(diagnostics).contains("gatewayStatisticsList"); assertThat(diagnostics).contains("addressResolutionStatistics"); assertThat(diagnostics).contains("\"userAgent\":\"" + userAgent + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); } private void validateGatewayModeQueryDiagnostics(String diagnostics, String userAgent) { assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).contains(("gatewayStatisticsList")); assertThat(diagnostics).contains("\"operationType\":\"Query\""); assertThat(diagnostics).contains("\"userAgent\":\"" + userAgent + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"regionsContacted\""); } @Test(groups = {"simple"}, dataProvider = "query", timeOut = TIMEOUT*2) public void queryDiagnosticsGatewayMode(String query, Boolean qmEnabled) { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); List<String> itemIdList = new ArrayList<>(); for (int i = 0; i < 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); containerGateway.createItem(internalObjectNode); if (i % 20 == 0) { itemIdList.add(internalObjectNode.getId()); } } boolean qroupByFirstResponse = true; if (qmEnabled != null) { options.setQueryMetricsEnabled(qmEnabled); } Iterator<FeedResponse<InternalObjectNode>> iterator = containerGateway .queryItems(query, options, InternalObjectNode.class) .iterableByPage() .iterator(); assertThat(iterator.hasNext()).isTrue(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); assertThat(feedResponse.getResults().size()).isEqualTo(0); if (!query.contains("group by") || qroupByFirstResponse) { validateQueryDiagnostics(queryDiagnostics, qmEnabled, true); validateGatewayModeQueryDiagnostics(queryDiagnostics, this.gatewayClientUserAgent); if (query.contains("group by")) { qroupByFirstResponse = false; } } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryMetricsWithADifferentLocale() { Locale.setDefault(Locale.GERMAN); String query = "select * from root where root.id= \"someid\""; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); Iterator<FeedResponse<InternalObjectNode>> iterator = this.containerGateway.queryItems(query, options, InternalObjectNode.class) .iterableByPage().iterator(); double requestCharge = 0; while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); requestCharge += feedResponse.getRequestCharge(); } assertThat(requestCharge).isGreaterThan(0); Locale.setDefault(Locale.ROOT); } private static void validateQueryDiagnostics( String queryDiagnostics, Boolean qmEnabled, boolean expectQueryPlanDiagnostics) { if (qmEnabled == null || qmEnabled) { assertThat(queryDiagnostics).contains("retrievedDocumentCount"); assertThat(queryDiagnostics).contains("queryPreparationTimes"); assertThat(queryDiagnostics).contains("runtimeExecutionTimes"); assertThat(queryDiagnostics).contains("fetchExecutionRanges"); } else { assertThat(queryDiagnostics).doesNotContain("retrievedDocumentCount"); assertThat(queryDiagnostics).doesNotContain("queryPreparationTimes"); assertThat(queryDiagnostics).doesNotContain("runtimeExecutionTimes"); assertThat(queryDiagnostics).doesNotContain("fetchExecutionRanges"); } if (expectQueryPlanDiagnostics) { assertThat(queryDiagnostics).contains("queryPlanDiagnosticsContext"); assertThat(queryDiagnostics).contains("startTimeUTC"); assertThat(queryDiagnostics).contains("endTimeUTC"); } else { assertThat(queryDiagnostics).contains("\"queryPlanDiagnosticsContext\":null"); } } @Test(groups = {"simple"}, dataProvider = "readAllItemsOfLogicalPartition", timeOut = TIMEOUT) public void queryMetricsForReadAllItemsOfLogicalPartition(Integer expectedItemCount, Boolean qmEnabled) { String pkValue = UUID.randomUUID().toString(); for (int i = 0; i < expectedItemCount; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(pkValue); CosmosItemResponse<InternalObjectNode> createResponse = containerGateway.createItem(internalObjectNode); } CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); if (qmEnabled != null) { options = options.setQueryMetricsEnabled(qmEnabled); } ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(options, 5); Iterator<FeedResponse<InternalObjectNode>> iterator = this.containerGateway .readAllItems( new PartitionKey(pkValue), options, InternalObjectNode.class) .iterableByPage().iterator(); assertThat(iterator.hasNext()).isTrue(); int actualItemCount = 0; while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); actualItemCount += feedResponse.getResults().size(); validateQueryDiagnostics(queryDiagnostics, qmEnabled, false); } assertThat(actualItemCount).isEqualTo(expectedItemCount); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnosticsOnException() throws Exception { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = null; try { createResponse = containerDirect.createItem(internalObjectNode); CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey")); CosmosItemResponse<InternalObjectNode> readResponse = containerDirect.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey("wrongPartitionKey"), InternalObjectNode.class); fail("request should fail as partition key is wrong"); } catch (CosmosException exception) { isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.directClientUserAgent + "\""); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(exception.getDiagnostics().getContactedRegionNames()).isNotEmpty(); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); assertThat(diagnostics).contains("\"backendLatencyInMs\""); assertThat(diagnostics).contains("\"retryAfterInMs\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"exceptionMessage\":\"[\\\"Resource Not Found."); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\":null"); isValidJSON(diagnostics); validateTransportRequestTimelineDirect(diagnostics); validateRegionContacted(createResponse.getDiagnostics(), directClient.asyncClient()); ObjectNode diagnosticsNode = (ObjectNode) OBJECT_MAPPER.readTree(diagnostics); JsonNode responseStatisticsList = diagnosticsNode.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); assertThat(responseStatisticsList.size()).isGreaterThan(0); JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); assertThat(storeResult).isNotNull(); JsonNode replicaStatusList = storeResult.get("replicaStatusList"); assertThat(replicaStatusList.isArray()).isTrue(); assertThat(replicaStatusList.size()).isGreaterThan(0); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnosticsOnMetadataException() { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosClient client = null; try { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer container = client.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); HttpClient mockHttpClient = Mockito.mock(HttpClient.class); Mockito.when(mockHttpClient.send(Mockito.any(HttpRequest.class), Mockito.any(Duration.class))) .thenReturn(Mono.error(new CosmosException(400, "TestBadRequest"))); RxStoreModel rxGatewayStoreModel = rxGatewayStoreModel = ReflectionUtils.getGatewayProxy((RxDocumentClientImpl) client.asyncClient().getDocClientWrapper()); ReflectionUtils.setGatewayHttpClient(rxGatewayStoreModel, mockHttpClient); container.createItem(internalObjectNode); fail("request should fail as bad request"); } catch (CosmosException exception) { isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.BADREQUEST); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("\"exceptionMessage\":\"TestBadRequest\""); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(diagnostics).contains("\"resourceType\":\"DocumentCollection\""); assertThat(exception.getDiagnostics().getContactedRegionNames()).isNotEmpty(); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); isValidJSON(diagnostics); } finally { if (client != null) { client.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void supplementalResponseStatisticsList() throws Exception { ClientSideRequestStatistics clientSideRequestStatistics = new ClientSideRequestStatistics(mockDiagnosticsClientContext()); for (int i = 0; i < 15; i++) { RxDocumentServiceRequest rxDocumentServiceRequest = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Head, ResourceType.Document); clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, null, null); } List<ClientSideRequestStatistics.StoreResponseStatistics> storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); ObjectMapper objectMapper = new ObjectMapper(); String diagnostics = objectMapper.writeValueAsString(clientSideRequestStatistics); JsonNode jsonNode = objectMapper.readTree(diagnostics); ArrayNode supplementalResponseStatisticsListNode = (ArrayNode) jsonNode.get("supplementalResponseStatisticsList"); assertThat(storeResponseStatistics.size()).isEqualTo(15); assertThat(supplementalResponseStatisticsListNode.size()).isEqualTo(10); clearStoreResponseStatistics(clientSideRequestStatistics); storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); assertThat(storeResponseStatistics.size()).isEqualTo(0); for (int i = 0; i < 7; i++) { RxDocumentServiceRequest rxDocumentServiceRequest = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Head, ResourceType.Document); clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, null, null); } storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); objectMapper = new ObjectMapper(); diagnostics = objectMapper.writeValueAsString(clientSideRequestStatistics); jsonNode = objectMapper.readTree(diagnostics); supplementalResponseStatisticsListNode = (ArrayNode) jsonNode.get("supplementalResponseStatisticsList"); assertThat(storeResponseStatistics.size()).isEqualTo(7); assertThat(supplementalResponseStatisticsListNode.size()).isEqualTo(7); for(JsonNode node : supplementalResponseStatisticsListNode) { assertThat(node.get("storeResult").asText()).isNotNull(); String requestResponseTimeUTC = node.get("requestResponseTimeUTC").asText(); Instant instant = Instant.from(RESPONSE_TIME_FORMATTER.parse(requestResponseTimeUTC)); assertThat(Instant.now().toEpochMilli() - instant.toEpochMilli()).isLessThan(5000); assertThat(node.get("requestResponseTimeUTC")).isNotNull(); assertThat(node.get("requestOperationType")).isNotNull(); assertThat(node.get("requestSessionToken")).isNotNull(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void serializationOnVariousScenarios() { CosmosDatabaseResponse cosmosDatabase = gatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).read(); String diagnostics = cosmosDatabase.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"DATABASE_DESERIALIZATION\""); CosmosContainerResponse containerResponse = this.containerGateway.read(); diagnostics = containerResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"CONTAINER_DESERIALIZATION\""); TestItem testItem = new TestItem(); testItem.id = "TestId"; testItem.mypk = "TestPk"; CosmosItemResponse<TestItem> itemResponse = this.containerGateway.createItem(testItem); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); testItem.id = "TestId2"; testItem.mypk = "TestPk"; itemResponse = this.containerGateway.createItem(testItem, new PartitionKey("TestPk"), null); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).doesNotContain("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).doesNotContain("\"serializationType\":\"ITEM_DESERIALIZATION\""); TestItem readTestItem = itemResponse.getItem(); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"ITEM_DESERIALIZATION\""); CosmosItemResponse<InternalObjectNode> readItemResponse = this.containerGateway.readItem(testItem.id, new PartitionKey(testItem.mypk), null, InternalObjectNode.class); InternalObjectNode properties = readItemResponse.getItem(); diagnostics = readItemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"ITEM_DESERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void rntbdRequestResponseLengthStatistics() throws Exception { TestItem testItem = new TestItem(); testItem.id = UUID.randomUUID().toString(); testItem.mypk = UUID.randomUUID().toString(); int testItemLength = OBJECT_MAPPER.writeValueAsBytes(testItem).length; CosmosContainer container = directClient.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()).getContainer(this.cosmosAsyncContainer.getId()); CosmosItemResponse<TestItem> createItemResponse = container.createItem(testItem); validate(createItemResponse.getDiagnostics(), testItemLength, ModelBridgeInternal.getPayloadLength(createItemResponse)); try { container.createItem(testItem); fail("expected to fail due to 409"); } catch (CosmosException e) { logger.info("Diagnostics are : {}", e.getDiagnostics()); String diagnostics = e.getDiagnostics().toString(); assertThat(diagnostics).contains("\"exceptionMessage\":\"[\\\"Resource with specified id or name already exists.\\\"]\""); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); validate(e.getDiagnostics(), testItemLength, 0); } CosmosItemResponse<TestItem> readItemResponse = container.readItem(testItem.id, new PartitionKey(testItem.mypk), TestItem.class); validate(readItemResponse.getDiagnostics(), 0, ModelBridgeInternal.getPayloadLength(readItemResponse)); CosmosItemResponse<Object> deleteItemResponse = container.deleteItem(testItem, null); validate(deleteItemResponse.getDiagnostics(), 0, 0); } @Test(groups = {"simple"}, dataProvider = "connectionStateListenerArgProvider", timeOut = TIMEOUT) public void rntbdStatistics(boolean connectionStateListenerEnabled) throws Exception { Instant beforeClientInitialization = Instant.now(); CosmosClient client1 = null; try { DirectConnectionConfig connectionConfig = DirectConnectionConfig.getDefaultConfig(); connectionConfig.setConnectionEndpointRediscoveryEnabled(connectionStateListenerEnabled); client1 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(connectionConfig) .buildClient(); TestItem testItem = new TestItem(); testItem.id = UUID.randomUUID().toString(); testItem.mypk = UUID.randomUUID().toString(); int testItemLength = OBJECT_MAPPER.writeValueAsBytes(testItem).length; CosmosContainer container = client1.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()).getContainer(this.cosmosAsyncContainer.getId()); Thread.sleep(1000); Instant beforeInitializingRntbdServiceEndpoint = Instant.now(); CosmosItemResponse<TestItem> operation1Response = container.upsertItem(testItem); Instant afterInitializingRntbdServiceEndpoint = Instant.now(); Thread.sleep(1000); Instant beforeOperation2 = Instant.now(); CosmosItemResponse<TestItem> operation2Response = container.upsertItem(testItem); Instant afterOperation2 = Instant.now(); Thread.sleep(1000); Instant beforeOperation3 = Instant.now(); CosmosItemResponse<TestItem> operation3Response = container.upsertItem(testItem); Instant afterOperation3 = Instant.now(); validateRntbdStatistics(operation3Response.getDiagnostics(), beforeClientInitialization, beforeInitializingRntbdServiceEndpoint, afterInitializingRntbdServiceEndpoint, beforeOperation2, afterOperation2, beforeOperation3, afterOperation3, connectionStateListenerEnabled); CosmosItemResponse<TestItem> readItemResponse = container.readItem(testItem.id, new PartitionKey(testItem.mypk), TestItem.class); validate(readItemResponse.getDiagnostics(), 0, ModelBridgeInternal.getPayloadLength(readItemResponse)); CosmosItemResponse<Object> deleteItemResponse = container.deleteItem(testItem, null); validate(deleteItemResponse.getDiagnostics(), 0, 0); } finally { LifeCycleUtils.closeQuietly(client1); } } private void validateRntbdStatistics(CosmosDiagnostics cosmosDiagnostics, Instant clientInitializationTime, Instant beforeInitializingRntbdServiceEndpoint, Instant afterInitializingRntbdServiceEndpoint, Instant beforeOperation2, Instant afterOperation2, Instant beforeOperation3, Instant afterOperation3, boolean connectionStateListenerEnabled) throws Exception { ObjectNode diagnostics = (ObjectNode) OBJECT_MAPPER.readTree(cosmosDiagnostics.toString()); JsonNode responseStatisticsList = diagnostics.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); assertThat(responseStatisticsList.size()).isGreaterThan(0); JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); assertThat(storeResult).isNotNull(); JsonNode replicaStatusList = storeResult.get("replicaStatusList"); assertThat(replicaStatusList.isArray()).isTrue(); assertThat(replicaStatusList.size()).isGreaterThan(0); JsonNode serviceEndpointStatistics = storeResult.get("serviceEndpointStatistics"); assertThat(serviceEndpointStatistics).isNotNull(); assertThat(serviceEndpointStatistics.get("availableChannels").asInt(-1)).isGreaterThan(0); assertThat(serviceEndpointStatistics.get("acquiredChannels").asInt(-1)).isEqualTo(0); assertThat(serviceEndpointStatistics.get("inflightRequests").asInt(-1)).isEqualTo(1); assertThat(serviceEndpointStatistics.get("isClosed").asBoolean()).isEqualTo(false); JsonNode channelStatistics = storeResult.get("channelStatistics"); assertThat(channelStatistics).isNotNull(); assertThat(channelStatistics.get("channelId").asText()).isNotEmpty(); assertThat(channelStatistics.get("channelTaskQueueSize").asInt(-1)).isGreaterThanOrEqualTo(0); assertThat(channelStatistics.get("pendingRequestsCount").asInt(-1)).isGreaterThanOrEqualTo(0); assertThat(channelStatistics.get("lastReadTime").asText()).isNotEmpty(); assertThat(channelStatistics.get("waitForConnectionInit").asText()).isNotEmpty(); JsonNode connectionStateListenerMetrics = serviceEndpointStatistics.get("cerMetrics"); if (connectionStateListenerEnabled) { assertThat(connectionStateListenerMetrics).isNotNull(); assertThat(connectionStateListenerMetrics.get("lastCallTimestamp")).isNull(); assertThat(connectionStateListenerMetrics.get("lastActionableContext")).isNull(); } else { assertThat(connectionStateListenerMetrics).isNull(); } Instant beforeInitializationThreshold = beforeInitializingRntbdServiceEndpoint.minusMillis(1); assertThat(Instant.parse(serviceEndpointStatistics.get("createdTime").asText())) .isAfterOrEqualTo(beforeInitializationThreshold); Instant afterInitializationThreshold = afterInitializingRntbdServiceEndpoint.plusMillis(2); assertThat(Instant.parse(serviceEndpointStatistics.get("createdTime").asText())) .isBeforeOrEqualTo(afterInitializationThreshold); Instant afterOperation2Threshold = afterOperation2.plusMillis(2); Instant beforeOperation2Threshold = beforeOperation2.minusMillis(2); assertThat(Instant.parse(serviceEndpointStatistics.get("lastRequestTime").asText())) .isAfterOrEqualTo(beforeOperation2Threshold.toString()) .isBeforeOrEqualTo(afterOperation2Threshold.toString()); assertThat(Instant.parse(serviceEndpointStatistics.get("lastSuccessfulRequestTime").asText())) .isAfterOrEqualTo(beforeOperation2Threshold.toString()) .isBeforeOrEqualTo(afterOperation2Threshold.toString()); } private void validate(CosmosDiagnostics cosmosDiagnostics, int expectedRequestPayloadSize, int expectedResponsePayloadSize) throws Exception { ObjectNode diagnostics = (ObjectNode) OBJECT_MAPPER.readTree(cosmosDiagnostics.toString()); JsonNode responseStatisticsList = diagnostics.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); assertThat(responseStatisticsList.size()).isGreaterThan(0); JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); boolean hasPayload = storeResult.get("exceptionMessage") == null; assertThat(storeResult).isNotNull(); assertThat(storeResult.get("rntbdRequestLengthInBytes").asInt(-1)).isGreaterThan(expectedRequestPayloadSize); assertThat(storeResult.get("rntbdRequestLengthInBytes").asInt(-1)).isGreaterThan(expectedRequestPayloadSize); assertThat(storeResult.get("requestPayloadLengthInBytes").asInt(-1)).isEqualTo(expectedRequestPayloadSize); if (hasPayload) { assertThat(storeResult.get("responsePayloadLengthInBytes").asInt(-1)).isEqualTo(expectedResponsePayloadSize); } assertThat(storeResult.get("rntbdResponseLengthInBytes").asInt(-1)).isGreaterThan(expectedResponsePayloadSize); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void addressResolutionStatistics() { CosmosClient client1 = null; CosmosClient client2 = null; String databaseId = DatabaseForTest.generateId(); String containerId = UUID.randomUUID().toString(); CosmosDatabase cosmosDatabase = null; CosmosContainer cosmosContainer = null; try { client1 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); client1.createDatabase(databaseId); cosmosDatabase = client1.getDatabase(databaseId); cosmosDatabase.createContainer(containerId, "/mypk"); InternalObjectNode internalObjectNode = getInternalObjectNode(); cosmosContainer = cosmosDatabase.getContainer(containerId); CosmosItemResponse<InternalObjectNode> writeResourceResponse = cosmosContainer.createItem(internalObjectNode); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("addressResolutionStatistics"); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("\"inflightRequest\":false"); assertThat(writeResourceResponse.getDiagnostics().toString()).doesNotContain("endTime=\"null\""); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("\"exceptionMessage\":null"); client2 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); cosmosDatabase = client2.getDatabase(databaseId); cosmosContainer = cosmosDatabase.getContainer(containerId); AsyncDocumentClient asyncDocumentClient = client2.asyncClient().getContextClient(); GlobalAddressResolver addressResolver = (GlobalAddressResolver) FieldUtils.readField(asyncDocumentClient, "addressResolver", true); @SuppressWarnings("rawtypes") Map addressCacheByEndpoint = (Map) FieldUtils.readField(addressResolver, "addressCacheByEndpoint", true); Object endpointCache = addressCacheByEndpoint.values().toArray()[0]; GatewayAddressCache addressCache = (GatewayAddressCache) FieldUtils.readField(endpointCache, "addressCache", true); HttpClient httpClient = httpClient(true); FieldUtils.writeField(addressCache, "httpClient", httpClient, true); new Thread(() -> { try { Thread.sleep(5000); HttpClient httpClient1 = httpClient(false); FieldUtils.writeField(addressCache, "httpClient", httpClient1, true); } catch (Exception e) { fail(e.getMessage()); } }).start(); PartitionKey partitionKey = new PartitionKey(internalObjectNode.get("mypk")); CosmosItemResponse<InternalObjectNode> readResourceResponse = cosmosContainer.readItem(internalObjectNode.getId(), partitionKey, new CosmosItemRequestOptions(), InternalObjectNode.class); assertThat(readResourceResponse.getDiagnostics().toString()).contains("addressResolutionStatistics"); assertThat(readResourceResponse.getDiagnostics().toString()).contains("\"inflightRequest\":false"); assertThat(readResourceResponse.getDiagnostics().toString()).doesNotContain("endTime=\"null\""); assertThat(readResourceResponse.getDiagnostics().toString()).contains("\"exceptionMessage\":\"io.netty" + ".channel.AbstractChannel$AnnotatedConnectException: Connection refused"); } catch (Exception ex) { logger.error("Error in test addressResolutionStatistics", ex); fail("This test should not throw exception " + ex); } finally { safeDeleteSyncDatabase(cosmosDatabase); if (client1 != null) { client1.close(); } if (client2 != null) { client2.close(); } } } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void responseStatisticRequestStartTimeUTCForDirectCall() { CosmosAsyncClient client = null; String databaseId = DatabaseForTest.generateId(); FaultInjectionRule faultInjectionRule = null; try { client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(TestConfigurations.HOST) .endToEndOperationLatencyPolicyConfig( new CosmosEndToEndOperationLatencyPolicyConfigBuilder(Duration.ofSeconds(2)).build() ).buildAsyncClient(); createDatabase(client, databaseId); CosmosAsyncContainer container = createCollection(client, databaseId, getCollectionDefinition()); TestItem testItem = TestItem.createNewItem(); container.createItem(testItem).block(); faultInjectionRule = new FaultInjectionRuleBuilder("PARTITION_IS_MIGRATING") .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.CREATE_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.PARTITION_IS_MIGRATING) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(faultInjectionRule)).block(); CosmosDiagnostics cosmosDiagnostics = null; try { cosmosDiagnostics = container.createItem(TestItem.createNewItem()) .block() .getDiagnostics(); } catch (Exception exception) { fail("Request should succeeded, but failed with " + exception); } List<ClientSideRequestStatistics> clientSideRequestStatistics = (List<ClientSideRequestStatistics>) cosmosDiagnostics.getClientSideRequestStatistics(); List<ClientSideRequestStatistics.StoreResponseStatistics> responseStatistic = clientSideRequestStatistics.get(0).getResponseStatisticsList(); assert responseStatistic.size() == 2; Instant firstRequestStartTime = responseStatistic.get(0).getRequestStartTimeUTC(); Instant secondRequestStartTime = responseStatistic.get(1).getRequestStartTimeUTC(); assert firstRequestStartTime != null && secondRequestStartTime != null; assert firstRequestStartTime != secondRequestStartTime; assert firstRequestStartTime.compareTo(secondRequestStartTime) < 0; } finally { if (faultInjectionRule != null) { faultInjectionRule.disable(); } safeClose(client); } } private InternalObjectNode getInternalObjectNode() { InternalObjectNode internalObjectNode = new InternalObjectNode(); String uuid = UUID.randomUUID().toString(); internalObjectNode.setId(uuid); BridgeInternal.setProperty(internalObjectNode, "mypk", uuid); return internalObjectNode; } private InternalObjectNode getInternalObjectNode(String pkValue) { InternalObjectNode internalObjectNode = new InternalObjectNode(); String uuid = UUID.randomUUID().toString(); internalObjectNode.setId(uuid); BridgeInternal.setProperty(internalObjectNode, "mypk", pkValue); return internalObjectNode; } private List<ClientSideRequestStatistics.StoreResponseStatistics> getStoreResponseStatistics(ClientSideRequestStatistics requestStatistics) throws Exception { Field storeResponseStatisticsField = ClientSideRequestStatistics.class.getDeclaredField("supplementalResponseStatisticsList"); storeResponseStatisticsField.setAccessible(true); @SuppressWarnings({"unchecked"}) List<ClientSideRequestStatistics.StoreResponseStatistics> list = (List<ClientSideRequestStatistics.StoreResponseStatistics>) storeResponseStatisticsField.get(requestStatistics); return list; } private void clearStoreResponseStatistics(ClientSideRequestStatistics requestStatistics) throws Exception { Field storeResponseStatisticsField = ClientSideRequestStatistics.class.getDeclaredField("supplementalResponseStatisticsList"); storeResponseStatisticsField.setAccessible(true); storeResponseStatisticsField.set(requestStatistics, new ArrayList<ClientSideRequestStatistics.StoreResponseStatistics>()); } private void validateTransportRequestTimelineGateway(String diagnostics) { assertThat(diagnostics).contains("\"eventName\":\"connectionConfigured\""); assertThat(diagnostics).contains("\"eventName\":\"requestSent\""); assertThat(diagnostics).contains("\"eventName\":\"transitTime\""); assertThat(diagnostics).contains("\"eventName\":\"received\""); } private void validateTransportRequestTimelineDirect(String diagnostics) { assertThat(diagnostics).contains("\"eventName\":\"created\""); assertThat(diagnostics).contains("\"eventName\":\"queued\""); assertThat(diagnostics).contains("\"eventName\":\"channelAcquisitionStarted\""); assertThat(diagnostics).contains("\"eventName\":\"pipelined\""); assertThat(diagnostics).contains("\"eventName\":\"transitTime\""); assertThat(diagnostics).contains("\"eventName\":\"decodeTime"); assertThat(diagnostics).contains("\"eventName\":\"received\""); assertThat(diagnostics).contains("\"eventName\":\"completed\""); assertThat(diagnostics).contains("\"startTimeUTC\""); assertThat(diagnostics).contains("\"durationInMilliSecs\""); } public void isValidJSON(final String json) { try { final JsonParser parser = new JsonFactory().createParser(json); while (parser.nextToken() != null) { } } catch (IOException ex) { fail("Diagnostic string is not in json format ", ex); } } private HttpClient httpClient(boolean fakeProxy) { HttpClientConfig httpClientConfig; if(fakeProxy) { httpClientConfig = new HttpClientConfig(new Configs()) .withProxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 8888))); } else { httpClientConfig = new HttpClientConfig(new Configs()); } return HttpClient.createFixed(httpClientConfig); } private IndexUtilizationInfo createFromJSONString(String jsonString) { ObjectMapper indexUtilizationInfoObjectMapper = new ObjectMapper(); IndexUtilizationInfo indexUtilizationInfo = null; try { indexUtilizationInfo = indexUtilizationInfoObjectMapper.readValue(jsonString, IndexUtilizationInfo.class); } catch (JsonProcessingException e) { logger.error("Json not correctly formed ", e); } return indexUtilizationInfo; } private void validateRegionContacted(CosmosDiagnostics cosmosDiagnostics, CosmosAsyncClient cosmosAsyncClient) throws Exception { RxDocumentClientImpl rxDocumentClient = (RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(cosmosAsyncClient); GlobalEndpointManager globalEndpointManager = ReflectionUtils.getGlobalEndpointManager(rxDocumentClient); LocationCache locationCache = ReflectionUtils.getLocationCache(globalEndpointManager); Field locationInfoField = LocationCache.class.getDeclaredField("locationInfo"); locationInfoField.setAccessible(true); Object locationInfo = locationInfoField.get(locationCache); Class<?> DatabaseAccountLocationsInfoClass = Class.forName("com.azure.cosmos.implementation.routing" + ".LocationCache$DatabaseAccountLocationsInfo"); Field availableWriteEndpointByLocation = DatabaseAccountLocationsInfoClass.getDeclaredField( "availableWriteEndpointByLocation"); availableWriteEndpointByLocation.setAccessible(true); @SuppressWarnings("unchecked") Map<String, URI> map = (Map<String, URI>) availableWriteEndpointByLocation.get(locationInfo); String regionName = map.keySet().iterator().next(); assertThat(cosmosDiagnostics.getContactedRegionNames().size()).isEqualTo(1); assertThat(cosmosDiagnostics.getContactedRegionNames().iterator().next()).isEqualTo(regionName.toLowerCase()); } private void validateChannelStatistics(CosmosDiagnostics cosmosDiagnostics) { for (ClientSideRequestStatistics clientSideRequestStatistics : cosmosDiagnostics.getClientSideRequestStatistics()) { for (ClientSideRequestStatistics.StoreResponseStatistics storeResponseStatistics : clientSideRequestStatistics.getResponseStatisticsList()) { assertThat(storeResponseStatistics).isNotNull(); RntbdChannelStatistics rntbdChannelStatistics = storeResponseStatistics .getStoreResult() .getStoreResponseDiagnostics() .getRntbdChannelStatistics(); assertThat(rntbdChannelStatistics).isNotNull(); try { String rntbdChannelStatisticsString = Utils.getSimpleObjectMapper().writeValueAsString(rntbdChannelStatistics); assertThat(rntbdChannelStatisticsString).contains("\"channelId\":\"" + rntbdChannelStatistics.getChannelId() + "\""); assertThat(rntbdChannelStatisticsString) .contains("\"channelTaskQueueSize\":" + rntbdChannelStatistics.getChannelTaskQueueSize()); assertThat(rntbdChannelStatisticsString) .contains("\"pendingRequestsCount\":" + rntbdChannelStatistics.getPendingRequestsCount()); assertThat(rntbdChannelStatisticsString) .contains("\"lastReadTime\":\"" + rntbdChannelStatistics.getLastReadTime() + "\""); if (rntbdChannelStatistics.getTransitTimeoutCount() > 0) { assertThat(rntbdChannelStatisticsString) .contains("\"transitTimeoutCount\":" + rntbdChannelStatistics.getTransitTimeoutCount()); assertThat(rntbdChannelStatisticsString) .contains("\"transitTimeoutStartingTime\":\"" + rntbdChannelStatistics.getTransitTimeoutStartingTime() + "\""); } else { assertThat(rntbdChannelStatisticsString) .doesNotContain("\"transitTimeoutCount\":" + rntbdChannelStatistics.getTransitTimeoutCount()); assertThat(rntbdChannelStatisticsString) .doesNotContain("\"transitTimeoutStartingTime\":\"" + rntbdChannelStatistics.getTransitTimeoutStartingTime() + "\""); } assertThat(rntbdChannelStatisticsString).contains("\"waitForConnectionInit\":" + rntbdChannelStatistics.isWaitForConnectionInit()); } catch (JsonProcessingException e) { fail("Failed to parse RntbdChannelStatistics"); } } } } private CosmosDiagnostics performDocumentOperation( CosmosAsyncContainer cosmosAsyncContainer, OperationType operationType, TestItem createdItem) { if (operationType == OperationType.Query) { String query = "SELECT * from c"; FeedResponse<TestItem> itemFeedResponse = cosmosAsyncContainer.queryItems(query, TestItem.class).byPage().blockFirst(); return itemFeedResponse.getCosmosDiagnostics(); } if (operationType == OperationType.Read) { return cosmosAsyncContainer .readItem(createdItem.id, new PartitionKey(createdItem.mypk), TestItem.class) .block() .getDiagnostics(); } if (operationType == OperationType.Replace) { return cosmosAsyncContainer .replaceItem(createdItem, createdItem.id, new PartitionKey(createdItem.mypk)) .block() .getDiagnostics(); } if (operationType == OperationType.Create) { return cosmosAsyncContainer.createItem(TestItem.createNewItem()).block().getDiagnostics(); } throw new IllegalArgumentException("The operation type is not supported"); } public static class TestItem { public String id; public String mypk; public TestItem() { } public TestItem(String id, String mypk) { this.id = id; this.mypk = mypk; } public static TestItem createNewItem() { return new TestItem(UUID.randomUUID().toString(), UUID.randomUUID().toString()); } } }
assertThat(queryDiagnostics).contains("endTimeUTC");
public void gatewayDiagnosticsOnException() throws Exception { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = null; try { createResponse = this.containerGateway.createItem(internalObjectNode); CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey")); CosmosItemResponse<InternalObjectNode> readResponse = this.containerGateway.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey("wrongPartitionKey"), InternalObjectNode.class); fail("request should fail as partition key is wrong"); } catch (CosmosException exception) { System.out.println(exception.getDiagnostics()); isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND); assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).contains("gatewayStatisticsList"); assertThat(diagnostics).contains("\"statusCode\":404"); assertThat(diagnostics).contains("\"operationType\":\"Read\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).contains("\"exceptionMessage\":\"Entity with the specified id does not exist in the system."); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(createResponse.getDiagnostics().getContactedRegionNames()).isNotNull(); validateRegionContacted(createResponse.getDiagnostics(), this.containerGateway.asyncContainer.getDatabase().getClient()); assertThat(createResponse.getDiagnostics().getRegionsContacted()).isNotEmpty(); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); validateTransportRequestTimelineGateway(diagnostics); isValidJSON(diagnostics); } }
class CosmosDiagnosticsTest extends TestSuiteBase { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final String USER_AGENT_SUFFIX_GATEWAY_CLIENT = "gatewayClientSuffix"; private static final String USER_AGENT_SUFFIX_DIRECT_CLIENT = "directClientSuffix"; private static final DateTimeFormatter RESPONSE_TIME_FORMATTER = DateTimeFormatter.ISO_INSTANT; private static final String tempMachineId = getTempMachineId(); private CosmosClient gatewayClient; private CosmosClient directClient; private CosmosAsyncDatabase cosmosAsyncDatabase; private CosmosContainer containerGateway; private CosmosContainer containerDirect; private CosmosAsyncContainer cosmosAsyncContainer; private String gatewayClientUserAgent; private String directClientUserAgent; private static String getTempMachineId() { Field field = null; try { field = RxDocumentClientImpl.class.getDeclaredField("tempMachineId"); } catch (NoSuchFieldException e) { fail(e.toString()); } field.setAccessible(true); try { return (String)field.get(null); } catch (IllegalAccessException e) { fail(e.toString()); return null; } } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { assertThat(this.gatewayClient).isNull(); gatewayClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .userAgentSuffix(USER_AGENT_SUFFIX_GATEWAY_CLIENT) .gatewayMode() .buildClient(); UserAgentContainer userAgentContainer = new UserAgentContainer(); userAgentContainer.setSuffix(USER_AGENT_SUFFIX_GATEWAY_CLIENT); this.gatewayClientUserAgent = userAgentContainer.getUserAgent(); directClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .userAgentSuffix(USER_AGENT_SUFFIX_DIRECT_CLIENT) .directMode() .buildClient(); userAgentContainer.setSuffix(USER_AGENT_SUFFIX_DIRECT_CLIENT); this.directClientUserAgent = userAgentContainer.getUserAgent(); cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(this.gatewayClient.asyncClient()); cosmosAsyncDatabase = directClient.asyncClient().getDatabase(cosmosAsyncContainer.getDatabase().getId()); containerGateway = gatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); containerDirect = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { if (this.gatewayClient != null) { this.gatewayClient.close(); } if (this.directClient != null) { this.directClient.close(); } } @DataProvider(name = "query") private Object[][] query() { return new Object[][]{ new Object[] { "Select * from c where c.id = 'wrongId'", true }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", true }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", true }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", true }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", true }, new Object[] { "Select * from c where c.id = 'wrongId'", false }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", false }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", false }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId'", false }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", false }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", false }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", false }, }; } @DataProvider(name = "readAllItemsOfLogicalPartition") private Object[][] readAllItemsOfLogicalPartition() { return new Object[][]{ new Object[] { 1, true }, new Object[] { 5, null }, new Object[] { 20, null }, new Object[] { 1, false }, new Object[] { 5, false }, new Object[] { 20, false }, }; } @DataProvider(name = "connectionStateListenerArgProvider") public Object[][] connectionStateListenerArgProvider() { return new Object[][]{ {true}, {false} }; } @DataProvider(name = "operationTypeProvider") public static Object[][] operationTypeProvider() { return new Object[][]{ { OperationType.Read }, { OperationType.Replace }, { OperationType.Create }, { OperationType.Query }, }; } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void gatewayDiagnostics() throws Exception { Thread.sleep(2000); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = containerGateway.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).contains("gatewayStatisticsList"); assertThat(diagnostics).contains("\"operationType\":\"Create\""); assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\""); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); assertThat(createResponse.getDiagnostics().getContactedRegionNames()).isNotNull(); assertThat(createResponse.getDiagnostics().getRegionsContacted()).isNotEmpty(); validateTransportRequestTimelineGateway(diagnostics); validateRegionContacted(createResponse.getDiagnostics(), gatewayClient.asyncClient()); isValidJSON(diagnostics); } @Test(groups = {"simple"}, timeOut = TIMEOUT)
class CosmosDiagnosticsTest extends TestSuiteBase { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final String USER_AGENT_SUFFIX_GATEWAY_CLIENT = "gatewayClientSuffix"; private static final String USER_AGENT_SUFFIX_DIRECT_CLIENT = "directClientSuffix"; private static final DateTimeFormatter RESPONSE_TIME_FORMATTER = DateTimeFormatter.ISO_INSTANT; private static final String tempMachineId = getTempMachineId(); private CosmosClient gatewayClient; private CosmosClient directClient; private CosmosAsyncDatabase cosmosAsyncDatabase; private CosmosContainer containerGateway; private CosmosContainer containerDirect; private CosmosAsyncContainer cosmosAsyncContainer; private String gatewayClientUserAgent; private String directClientUserAgent; private static String getTempMachineId() { Field field = null; try { field = RxDocumentClientImpl.class.getDeclaredField("tempMachineId"); } catch (NoSuchFieldException e) { fail(e.toString()); } field.setAccessible(true); try { return (String)field.get(null); } catch (IllegalAccessException e) { fail(e.toString()); return null; } } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { assertThat(this.gatewayClient).isNull(); gatewayClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .userAgentSuffix(USER_AGENT_SUFFIX_GATEWAY_CLIENT) .gatewayMode() .buildClient(); UserAgentContainer userAgentContainer = new UserAgentContainer(); userAgentContainer.setSuffix(USER_AGENT_SUFFIX_GATEWAY_CLIENT); this.gatewayClientUserAgent = userAgentContainer.getUserAgent(); directClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .userAgentSuffix(USER_AGENT_SUFFIX_DIRECT_CLIENT) .directMode() .buildClient(); userAgentContainer.setSuffix(USER_AGENT_SUFFIX_DIRECT_CLIENT); this.directClientUserAgent = userAgentContainer.getUserAgent(); cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(this.gatewayClient.asyncClient()); cosmosAsyncDatabase = directClient.asyncClient().getDatabase(cosmosAsyncContainer.getDatabase().getId()); containerGateway = gatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); containerDirect = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { if (this.gatewayClient != null) { this.gatewayClient.close(); } if (this.directClient != null) { this.directClient.close(); } } @DataProvider(name = "query") private Object[][] query() { return new Object[][]{ new Object[] { "Select * from c where c.id = 'wrongId'", true }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", true }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", true }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", true }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", true }, new Object[] { "Select * from c where c.id = 'wrongId'", false }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", false }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", false }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId'", false }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", false }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", false }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", false }, }; } @DataProvider(name = "readAllItemsOfLogicalPartition") private Object[][] readAllItemsOfLogicalPartition() { return new Object[][]{ new Object[] { 1, true }, new Object[] { 5, null }, new Object[] { 20, null }, new Object[] { 1, false }, new Object[] { 5, false }, new Object[] { 20, false }, }; } @DataProvider(name = "connectionStateListenerArgProvider") public Object[][] connectionStateListenerArgProvider() { return new Object[][]{ {true}, {false} }; } @DataProvider(name = "operationTypeProvider") public static Object[][] operationTypeProvider() { return new Object[][]{ { OperationType.Read }, { OperationType.Replace }, { OperationType.Create }, { OperationType.Query }, }; } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void gatewayDiagnostics() throws Exception { Thread.sleep(2000); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = containerGateway.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).contains("gatewayStatisticsList"); assertThat(diagnostics).contains("\"operationType\":\"Create\""); assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\""); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); assertThat(createResponse.getDiagnostics().getContactedRegionNames()).isNotNull(); assertThat(createResponse.getDiagnostics().getRegionsContacted()).isNotEmpty(); validateTransportRequestTimelineGateway(diagnostics); validateRegionContacted(createResponse.getDiagnostics(), gatewayClient.asyncClient()); isValidJSON(diagnostics); } @Test(groups = {"simple"}, timeOut = TIMEOUT) @Test(groups = {"simple"}, timeOut = TIMEOUT) public void systemDiagnosticsForSystemStateInformation() { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = this.containerGateway.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("systemInformation"); assertThat(diagnostics).contains("usedMemory"); assertThat(diagnostics).contains("availableMemory"); assertThat(diagnostics).contains("systemCpuLoad"); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnostics() throws Exception { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = containerDirect.createItem(internalObjectNode); validateDirectModeDiagnosticsOnSuccess(createResponse.getDiagnostics(), directClient, this.directClientUserAgent); try { containerDirect.createItem(internalObjectNode); fail("expected 409"); } catch (CosmosException e) { validateDirectModeDiagnosticsOnException(e, this.directClientUserAgent); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void requestSessionTokenDiagnostics() { CosmosClient testSessionTokenClient = null; try { testSessionTokenClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .consistencyLevel(ConsistencyLevel.SESSION) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer cosmosContainer = testSessionTokenClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"requestSessionToken\":null"); String sessionToken = createResponse.getSessionToken(); CosmosItemResponse<InternalObjectNode> readResponse = cosmosContainer.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey(BridgeInternal.getProperties(createResponse).getId()), InternalObjectNode.class); diagnostics = readResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"requestSessionToken\":\"%s\"", sessionToken)); CosmosBatch batch = CosmosBatch.createCosmosBatch(new PartitionKey( BridgeInternal.getProperties(createResponse).getId())); internalObjectNode = getInternalObjectNode(); batch.createItemOperation(internalObjectNode); CosmosBatchResponse batchResponse = cosmosContainer.executeCosmosBatch(batch, new CosmosBatchRequestOptions().setSessionToken(readResponse.getSessionToken())); diagnostics = batchResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"requestSessionToken\":\"%s\"", readResponse.getSessionToken())); } finally { if (testSessionTokenClient != null) { testSessionTokenClient.close(); } } } @Test(groups = {"simple"}) public void databaseAccountToClients() { CosmosClient testClient = null; try { testClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer cosmosContainer = testClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"clientEndpoints\"" + ":{\"%s\"", TestConfigurations.HOST)); int clientsIndex = diagnostics.indexOf("\"clientEndpoints\":"); String[] substrings = diagnostics.substring(clientsIndex, clientsIndex + 120) .split("}")[0].split(":"); String intString = substrings[substrings.length-1]; int intValue = Integer.parseInt(intString); CosmosClient testClient2 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); internalObjectNode = getInternalObjectNode(); createResponse = cosmosContainer.createItem(internalObjectNode); diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"clientEndpoints\"" + ":{\"%s\"", TestConfigurations.HOST)); clientsIndex = diagnostics.indexOf("\"clientEndpoints\":"); substrings = diagnostics.substring(clientsIndex, clientsIndex + 120) .split("}")[0].split(":"); intString = substrings[substrings.length-1]; assertThat(Integer.parseInt(intString)).isEqualTo(intValue+1); testClient2.close(); } finally { if (testClient != null) { testClient.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryPlanDiagnostics() throws JsonProcessingException { List<String> itemIdList = new ArrayList<>(); for(int i = 0; i< 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = containerDirect.createItem(internalObjectNode); if(i%20 == 0) { itemIdList.add(internalObjectNode.getId()); } } String queryDiagnostics = null; List<String> queryList = new ArrayList<>(); queryList.add("Select * from c"); StringBuilder queryBuilder = new StringBuilder("SELECT * from c where c.mypk in ("); for(int i = 0 ; i < itemIdList.size(); i++){ queryBuilder.append("'").append(itemIdList.get(i)).append("'"); if(i < (itemIdList.size()-1)) { queryBuilder.append(","); } else { queryBuilder.append(")"); } } queryList.add(queryBuilder.toString()); queryList.add("Select * from c where c.id = 'wrongId'"); for(String query : queryList) { int feedResponseCounter = 0; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setQueryMetricsEnabled(true); Iterator<FeedResponse<InternalObjectNode>> iterator = containerDirect.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); if (feedResponseCounter == 0) { assertThat(queryDiagnostics).contains("queryPlanDiagnosticsContext"); assertThat(queryDiagnostics).contains("startTimeUTC"); assertThat(queryDiagnostics).contains("endTimeUTC"); assertThat(queryDiagnostics).contains("durationInMilliSecs"); String requestTimeLine = OBJECT_MAPPER.writeValueAsString(feedResponse.getCosmosDiagnostics().getFeedResponseDiagnostics().getQueryPlanDiagnosticsContext().getRequestTimeline()); assertThat(requestTimeLine).contains("connectionConfigured"); assertThat(requestTimeLine).contains("requestSent"); assertThat(requestTimeLine).contains("transitTime"); assertThat(requestTimeLine).contains("received"); } else { assertThat(queryDiagnostics).contains("\"queryPlanDiagnosticsContext\":null"); } feedResponseCounter++; } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readManyDiagnostics() { String pkValue = UUID.randomUUID().toString(); PartitionKey partitionKey = new PartitionKey(pkValue); List<CosmosItemIdentity> itemIdList = new ArrayList<>(); for(int i = 0; i< 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(pkValue); CosmosItemResponse<InternalObjectNode> createResponse = containerDirect.createItem(internalObjectNode); if(i%20 == 0) { itemIdList.add(new CosmosItemIdentity(partitionKey, internalObjectNode.getId())); } } FeedResponse<InternalObjectNode> response = containerDirect.readMany(itemIdList, InternalObjectNode.class); FeedResponseDiagnostics diagnostics = response.getCosmosDiagnostics().getFeedResponseDiagnostics(); assertThat(diagnostics.getClientSideRequestStatistics().size()).isEqualTo(1); assertThat(diagnostics.getQueryMetricsMap().values().iterator().next().getRetrievedDocumentCount()).isEqualTo(itemIdList.size()); String cosmosDiagnosticsString = response.getCosmosDiagnostics().toString(); assertThat(cosmosDiagnosticsString).contains("\"userAgent\":\"" + this.directClientUserAgent + "\""); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryMetricsWithIndexMetrics() { List<String> itemIdList = new ArrayList<>(); for(int i = 0; i< 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = containerDirect.createItem(internalObjectNode); if(i%20 == 0) { itemIdList.add(internalObjectNode.getId()); } } String queryDiagnostics = null; List<String> queryList = new ArrayList<>(); StringBuilder queryBuilder = new StringBuilder("SELECT * from c where c.mypk in ("); for(int i = 0 ; i < itemIdList.size(); i++){ queryBuilder.append("'").append(itemIdList.get(i)).append("'"); if(i < (itemIdList.size()-1)) { queryBuilder.append(","); } else { queryBuilder.append(")"); } } queryList.add(queryBuilder.toString()); for (String query : queryList) { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setQueryMetricsEnabled(true); options.setIndexMetricsEnabled(true); Iterator<FeedResponse<InternalObjectNode>> iterator = containerDirect.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); logger.info("This is query diagnostics {}", queryDiagnostics); if (feedResponse.getResponseHeaders().containsKey(HttpConstants.HttpHeaders.INDEX_UTILIZATION)) { assertThat(feedResponse.getResponseHeaders().get(HttpConstants.HttpHeaders.INDEX_UTILIZATION)).isNotNull(); assertThat(createFromJSONString(Utils.decodeBase64String(feedResponse.getResponseHeaders().get(HttpConstants.HttpHeaders.INDEX_UTILIZATION))).getUtilizedSingleIndexes()).isNotNull(); } } } } @Test(groups = {"simple"}, dataProvider = "query", timeOut = TIMEOUT) public void queryMetrics(String query, Boolean qmEnabled) { CosmosContainer directContainer = this.directClient.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()) .getContainer(this.cosmosAsyncContainer.getId()); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); if (qmEnabled != null) { options.setQueryMetricsEnabled(qmEnabled); } boolean qroupByFirstResponse = true; Iterator<FeedResponse<InternalObjectNode>> iterator = directContainer.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); assertThat(iterator.hasNext()).isTrue(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); assertThat(feedResponse.getResults().size()).isEqualTo(0); if (!query.contains("group by") || qroupByFirstResponse) { validateQueryDiagnostics(queryDiagnostics, qmEnabled, true); validateDirectModeQueryDiagnostics(queryDiagnostics, this.directClientUserAgent); if (query.contains("group by")) { qroupByFirstResponse = false; } } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryDiagnosticsOnOrderBy() { String containerId = "testcontainer"; cosmosAsyncDatabase.createContainer(containerId, "/mypk", ThroughputProperties.createManualThroughput(40000)).block(); CosmosAsyncContainer testcontainer = cosmosAsyncDatabase.getContainer(containerId); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setConsistencyLevel(ConsistencyLevel.EVENTUAL); testcontainer.createItem(getInternalObjectNode()).block(); options.setMaxDegreeOfParallelism(-1); String query = "SELECT * from c ORDER BY c._ts DESC"; CosmosPagedFlux<InternalObjectNode> cosmosPagedFlux = testcontainer.queryItems(query, options, InternalObjectNode.class); Set<String> partitionKeyRangeIds = new HashSet<>(); Set<String> pkRids = new HashSet<>(); cosmosPagedFlux.byPage().flatMap(feedResponse -> { String cosmosDiagnosticsString = feedResponse.getCosmosDiagnostics().toString(); Pattern pattern = Pattern.compile("(\"partitionKeyRangeId\":\")(\\d)"); Matcher matcher = pattern.matcher(cosmosDiagnosticsString); while (matcher.find()) { String group = matcher.group(2); partitionKeyRangeIds.add(group); } pattern = Pattern.compile("(pkrId:)(\\d)"); matcher = pattern.matcher(cosmosDiagnosticsString); while (matcher.find()) { String group = matcher.group(2); pkRids.add(group); } return Flux.just(feedResponse); }).blockLast(); assertThat(pkRids).isNotEmpty(); assertThat(pkRids).isEqualTo(partitionKeyRangeIds); deleteCollection(testcontainer); } @Test(groups = {"simple"}, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) public void directDiagnosticsOnCancelledOperation(OperationType operationType) { CosmosAsyncClient client = null; FaultInjectionRule faultInjectionRule = null; try { client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(TestConfigurations.HOST) .endToEndOperationLatencyPolicyConfig( new CosmosEndToEndOperationLatencyPolicyConfigBuilder(Duration.ofSeconds(1)).build() ).buildAsyncClient(); CosmosAsyncContainer container = client.getDatabase(containerDirect.asyncContainer.getDatabase().getId()).getContainer(containerDirect.getId()); TestItem testItem = TestItem.createNewItem(); container.createItem(testItem).block(); faultInjectionRule = new FaultInjectionRuleBuilder("responseDelay") .condition(new FaultInjectionConditionBuilder().build()) .result( FaultInjectionResultBuilders.getResultBuilder(FaultInjectionServerErrorType.RESPONSE_DELAY) .delay(Duration.ofSeconds(2)) .build() ) .build(); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(faultInjectionRule)).block(); this.performDocumentOperation(container, operationType, testItem); fail("expected OperationCancelledException"); } catch (CosmosException e) { assertThat(e).isInstanceOf(OperationCancelledException.class); String cosmosDiagnosticsString = e.getDiagnostics().toString(); assertThat(cosmosDiagnosticsString).contains("\"statusCode\":408"); assertThat(cosmosDiagnosticsString).contains("\"subStatusCode\":20008"); } finally { if (faultInjectionRule != null) { faultInjectionRule.disable(); } safeClose(client); } } @Test(groups = {"simple"}, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) public void directDiagnostics_WithFaultInjection(OperationType operationType) { CosmosAsyncClient client = null; FaultInjectionRule faultInjectionRule = null; try { client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(TestConfigurations.HOST) .buildAsyncClient(); CosmosAsyncContainer container = client.getDatabase(containerDirect.asyncContainer.getDatabase().getId()).getContainer(containerDirect.getId()); TestItem testItem = TestItem.createNewItem(); container.createItem(testItem).block(); faultInjectionRule = new FaultInjectionRuleBuilder("serverResponseError") .condition(new FaultInjectionConditionBuilder().build()) .result( FaultInjectionResultBuilders.getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .build(); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(faultInjectionRule)).block(); CosmosDiagnostics cosmosDiagnostics = this.performDocumentOperation(container, operationType, testItem); assertThat(cosmosDiagnostics).isNotNull(); String diagnosticsString = cosmosDiagnostics.toString(); assertThat(diagnosticsString).contains("\"statusCode\":410"); assertThat(diagnosticsString).contains("\"subStatusCode\":21005"); assertThat(diagnosticsString).doesNotContain("\"statusCode\":408"); assertThat(diagnosticsString).doesNotContain("\"subStatusCode\":20008"); } catch (CosmosException e) { fail("Request should succeeded but failed with " + e.getMessage()); } finally { if (faultInjectionRule != null) { faultInjectionRule.disable(); } safeClose(client); } } private void validateDirectModeDiagnosticsOnSuccess( CosmosDiagnostics cosmosDiagnostics, CosmosClient testDirectClient, String userAgent) throws Exception { String diagnostics = cosmosDiagnostics.toString(); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("supplementalResponseStatisticsList"); assertThat(diagnostics).contains("gatewayStatisticsList"); assertThat(diagnostics).contains("addressResolutionStatistics"); assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\""); assertThat(diagnostics).contains("\"metaDataName\":\"PARTITION_KEY_RANGE_LOOK_UP\""); assertThat(diagnostics).contains("\"metaDataName\":\"SERVER_ADDRESS_LOOKUP\""); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + userAgent + "\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"backendLatencyInMs\""); assertThat(diagnostics).contains("\"retryAfterInMs\""); assertThat(diagnostics).contains("\"channelStatistics\""); assertThat(cosmosDiagnostics.getContactedRegionNames()).isNotEmpty(); assertThat(cosmosDiagnostics.getDuration()).isNotNull(); validateTransportRequestTimelineDirect(diagnostics); validateRegionContacted(cosmosDiagnostics, testDirectClient.asyncClient()); validateChannelStatistics(cosmosDiagnostics); isValidJSON(diagnostics); } private void validateDirectModeDiagnosticsOnException(CosmosException cosmosException, String userAgent) { CosmosDiagnostics cosmosDiagnostics = cosmosException.getDiagnostics(); String diagnosticsString = cosmosDiagnostics.toString(); assertThat(diagnosticsString).contains("\"backendLatencyInMs\""); assertThat(diagnosticsString).contains("\"userAgent\":\"" + userAgent + "\""); assertThat(diagnosticsString).contains("\"retryAfterInMs\""); assertThat(diagnosticsString).contains("\"exceptionMessage\":\"[\\\"Resource with specified id or name already exists.\\\"]\""); assertThat(diagnosticsString).contains("\"exceptionResponseHeaders\""); assertThat(diagnosticsString).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); validateTransportRequestTimelineDirect(diagnosticsString); validateChannelStatistics(cosmosDiagnostics); if (!(cosmosException instanceof OperationCancelledException)) { assertThat(diagnosticsString).doesNotContain("\"statusCode\":408"); assertThat(diagnosticsString).doesNotContain("\"subStatusCode\":20008"); } } private void validateDirectModeQueryDiagnostics(String diagnostics, String userAgent) { assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("supplementalResponseStatisticsList"); assertThat(diagnostics).contains("responseStatisticsList"); assertThat(diagnostics).contains("gatewayStatisticsList"); assertThat(diagnostics).contains("addressResolutionStatistics"); assertThat(diagnostics).contains("\"userAgent\":\"" + userAgent + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); } private void validateGatewayModeQueryDiagnostics(String diagnostics, String userAgent) { assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).contains(("gatewayStatisticsList")); assertThat(diagnostics).contains("\"operationType\":\"Query\""); assertThat(diagnostics).contains("\"userAgent\":\"" + userAgent + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"regionsContacted\""); } @Test(groups = {"simple"}, dataProvider = "query", timeOut = TIMEOUT*2) public void queryDiagnosticsGatewayMode(String query, Boolean qmEnabled) { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); List<String> itemIdList = new ArrayList<>(); for (int i = 0; i < 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); containerGateway.createItem(internalObjectNode); if (i % 20 == 0) { itemIdList.add(internalObjectNode.getId()); } } boolean qroupByFirstResponse = true; if (qmEnabled != null) { options.setQueryMetricsEnabled(qmEnabled); } Iterator<FeedResponse<InternalObjectNode>> iterator = containerGateway .queryItems(query, options, InternalObjectNode.class) .iterableByPage() .iterator(); assertThat(iterator.hasNext()).isTrue(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); assertThat(feedResponse.getResults().size()).isEqualTo(0); if (!query.contains("group by") || qroupByFirstResponse) { validateQueryDiagnostics(queryDiagnostics, qmEnabled, true); validateGatewayModeQueryDiagnostics(queryDiagnostics, this.gatewayClientUserAgent); if (query.contains("group by")) { qroupByFirstResponse = false; } } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryMetricsWithADifferentLocale() { Locale.setDefault(Locale.GERMAN); String query = "select * from root where root.id= \"someid\""; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); Iterator<FeedResponse<InternalObjectNode>> iterator = this.containerGateway.queryItems(query, options, InternalObjectNode.class) .iterableByPage().iterator(); double requestCharge = 0; while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); requestCharge += feedResponse.getRequestCharge(); } assertThat(requestCharge).isGreaterThan(0); Locale.setDefault(Locale.ROOT); } private static void validateQueryDiagnostics( String queryDiagnostics, Boolean qmEnabled, boolean expectQueryPlanDiagnostics) { if (qmEnabled == null || qmEnabled) { assertThat(queryDiagnostics).contains("retrievedDocumentCount"); assertThat(queryDiagnostics).contains("queryPreparationTimes"); assertThat(queryDiagnostics).contains("runtimeExecutionTimes"); assertThat(queryDiagnostics).contains("fetchExecutionRanges"); } else { assertThat(queryDiagnostics).doesNotContain("retrievedDocumentCount"); assertThat(queryDiagnostics).doesNotContain("queryPreparationTimes"); assertThat(queryDiagnostics).doesNotContain("runtimeExecutionTimes"); assertThat(queryDiagnostics).doesNotContain("fetchExecutionRanges"); } if (expectQueryPlanDiagnostics) { assertThat(queryDiagnostics).contains("queryPlanDiagnosticsContext"); assertThat(queryDiagnostics).contains("startTimeUTC"); assertThat(queryDiagnostics).contains("endTimeUTC"); } else { assertThat(queryDiagnostics).contains("\"queryPlanDiagnosticsContext\":null"); } } @Test(groups = {"simple"}, dataProvider = "readAllItemsOfLogicalPartition", timeOut = TIMEOUT) public void queryMetricsForReadAllItemsOfLogicalPartition(Integer expectedItemCount, Boolean qmEnabled) { String pkValue = UUID.randomUUID().toString(); for (int i = 0; i < expectedItemCount; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(pkValue); CosmosItemResponse<InternalObjectNode> createResponse = containerGateway.createItem(internalObjectNode); } CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); if (qmEnabled != null) { options = options.setQueryMetricsEnabled(qmEnabled); } ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(options, 5); Iterator<FeedResponse<InternalObjectNode>> iterator = this.containerGateway .readAllItems( new PartitionKey(pkValue), options, InternalObjectNode.class) .iterableByPage().iterator(); assertThat(iterator.hasNext()).isTrue(); int actualItemCount = 0; while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); actualItemCount += feedResponse.getResults().size(); validateQueryDiagnostics(queryDiagnostics, qmEnabled, false); } assertThat(actualItemCount).isEqualTo(expectedItemCount); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnosticsOnException() throws Exception { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = null; try { createResponse = containerDirect.createItem(internalObjectNode); CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey")); CosmosItemResponse<InternalObjectNode> readResponse = containerDirect.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey("wrongPartitionKey"), InternalObjectNode.class); fail("request should fail as partition key is wrong"); } catch (CosmosException exception) { isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.directClientUserAgent + "\""); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(exception.getDiagnostics().getContactedRegionNames()).isNotEmpty(); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); assertThat(diagnostics).contains("\"backendLatencyInMs\""); assertThat(diagnostics).contains("\"retryAfterInMs\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"exceptionMessage\":\"[\\\"Resource Not Found."); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\":null"); isValidJSON(diagnostics); validateTransportRequestTimelineDirect(diagnostics); validateRegionContacted(createResponse.getDiagnostics(), directClient.asyncClient()); ObjectNode diagnosticsNode = (ObjectNode) OBJECT_MAPPER.readTree(diagnostics); JsonNode responseStatisticsList = diagnosticsNode.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); assertThat(responseStatisticsList.size()).isGreaterThan(0); JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); assertThat(storeResult).isNotNull(); JsonNode replicaStatusList = storeResult.get("replicaStatusList"); assertThat(replicaStatusList.isArray()).isTrue(); assertThat(replicaStatusList.size()).isGreaterThan(0); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnosticsOnMetadataException() { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosClient client = null; try { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer container = client.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); HttpClient mockHttpClient = Mockito.mock(HttpClient.class); Mockito.when(mockHttpClient.send(Mockito.any(HttpRequest.class), Mockito.any(Duration.class))) .thenReturn(Mono.error(new CosmosException(400, "TestBadRequest"))); RxStoreModel rxGatewayStoreModel = rxGatewayStoreModel = ReflectionUtils.getGatewayProxy((RxDocumentClientImpl) client.asyncClient().getDocClientWrapper()); ReflectionUtils.setGatewayHttpClient(rxGatewayStoreModel, mockHttpClient); container.createItem(internalObjectNode); fail("request should fail as bad request"); } catch (CosmosException exception) { isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.BADREQUEST); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("\"exceptionMessage\":\"TestBadRequest\""); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(diagnostics).contains("\"resourceType\":\"DocumentCollection\""); assertThat(exception.getDiagnostics().getContactedRegionNames()).isNotEmpty(); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); isValidJSON(diagnostics); } finally { if (client != null) { client.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void supplementalResponseStatisticsList() throws Exception { ClientSideRequestStatistics clientSideRequestStatistics = new ClientSideRequestStatistics(mockDiagnosticsClientContext()); for (int i = 0; i < 15; i++) { RxDocumentServiceRequest rxDocumentServiceRequest = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Head, ResourceType.Document); clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, null, null); } List<ClientSideRequestStatistics.StoreResponseStatistics> storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); ObjectMapper objectMapper = new ObjectMapper(); String diagnostics = objectMapper.writeValueAsString(clientSideRequestStatistics); JsonNode jsonNode = objectMapper.readTree(diagnostics); ArrayNode supplementalResponseStatisticsListNode = (ArrayNode) jsonNode.get("supplementalResponseStatisticsList"); assertThat(storeResponseStatistics.size()).isEqualTo(15); assertThat(supplementalResponseStatisticsListNode.size()).isEqualTo(10); clearStoreResponseStatistics(clientSideRequestStatistics); storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); assertThat(storeResponseStatistics.size()).isEqualTo(0); for (int i = 0; i < 7; i++) { RxDocumentServiceRequest rxDocumentServiceRequest = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Head, ResourceType.Document); clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, null, null); } storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); objectMapper = new ObjectMapper(); diagnostics = objectMapper.writeValueAsString(clientSideRequestStatistics); jsonNode = objectMapper.readTree(diagnostics); supplementalResponseStatisticsListNode = (ArrayNode) jsonNode.get("supplementalResponseStatisticsList"); assertThat(storeResponseStatistics.size()).isEqualTo(7); assertThat(supplementalResponseStatisticsListNode.size()).isEqualTo(7); for(JsonNode node : supplementalResponseStatisticsListNode) { assertThat(node.get("storeResult").asText()).isNotNull(); String requestResponseTimeUTC = node.get("requestResponseTimeUTC").asText(); Instant instant = Instant.from(RESPONSE_TIME_FORMATTER.parse(requestResponseTimeUTC)); assertThat(Instant.now().toEpochMilli() - instant.toEpochMilli()).isLessThan(5000); assertThat(node.get("requestResponseTimeUTC")).isNotNull(); assertThat(node.get("requestOperationType")).isNotNull(); assertThat(node.get("requestSessionToken")).isNotNull(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void serializationOnVariousScenarios() { CosmosDatabaseResponse cosmosDatabase = gatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).read(); String diagnostics = cosmosDatabase.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"DATABASE_DESERIALIZATION\""); CosmosContainerResponse containerResponse = this.containerGateway.read(); diagnostics = containerResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"CONTAINER_DESERIALIZATION\""); TestItem testItem = new TestItem(); testItem.id = "TestId"; testItem.mypk = "TestPk"; CosmosItemResponse<TestItem> itemResponse = this.containerGateway.createItem(testItem); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); testItem.id = "TestId2"; testItem.mypk = "TestPk"; itemResponse = this.containerGateway.createItem(testItem, new PartitionKey("TestPk"), null); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).doesNotContain("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).doesNotContain("\"serializationType\":\"ITEM_DESERIALIZATION\""); TestItem readTestItem = itemResponse.getItem(); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"ITEM_DESERIALIZATION\""); CosmosItemResponse<InternalObjectNode> readItemResponse = this.containerGateway.readItem(testItem.id, new PartitionKey(testItem.mypk), null, InternalObjectNode.class); InternalObjectNode properties = readItemResponse.getItem(); diagnostics = readItemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"ITEM_DESERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + this.gatewayClientUserAgent + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void rntbdRequestResponseLengthStatistics() throws Exception { TestItem testItem = new TestItem(); testItem.id = UUID.randomUUID().toString(); testItem.mypk = UUID.randomUUID().toString(); int testItemLength = OBJECT_MAPPER.writeValueAsBytes(testItem).length; CosmosContainer container = directClient.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()).getContainer(this.cosmosAsyncContainer.getId()); CosmosItemResponse<TestItem> createItemResponse = container.createItem(testItem); validate(createItemResponse.getDiagnostics(), testItemLength, ModelBridgeInternal.getPayloadLength(createItemResponse)); try { container.createItem(testItem); fail("expected to fail due to 409"); } catch (CosmosException e) { logger.info("Diagnostics are : {}", e.getDiagnostics()); String diagnostics = e.getDiagnostics().toString(); assertThat(diagnostics).contains("\"exceptionMessage\":\"[\\\"Resource with specified id or name already exists.\\\"]\""); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); validate(e.getDiagnostics(), testItemLength, 0); } CosmosItemResponse<TestItem> readItemResponse = container.readItem(testItem.id, new PartitionKey(testItem.mypk), TestItem.class); validate(readItemResponse.getDiagnostics(), 0, ModelBridgeInternal.getPayloadLength(readItemResponse)); CosmosItemResponse<Object> deleteItemResponse = container.deleteItem(testItem, null); validate(deleteItemResponse.getDiagnostics(), 0, 0); } @Test(groups = {"simple"}, dataProvider = "connectionStateListenerArgProvider", timeOut = TIMEOUT) public void rntbdStatistics(boolean connectionStateListenerEnabled) throws Exception { Instant beforeClientInitialization = Instant.now(); CosmosClient client1 = null; try { DirectConnectionConfig connectionConfig = DirectConnectionConfig.getDefaultConfig(); connectionConfig.setConnectionEndpointRediscoveryEnabled(connectionStateListenerEnabled); client1 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(connectionConfig) .buildClient(); TestItem testItem = new TestItem(); testItem.id = UUID.randomUUID().toString(); testItem.mypk = UUID.randomUUID().toString(); int testItemLength = OBJECT_MAPPER.writeValueAsBytes(testItem).length; CosmosContainer container = client1.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()).getContainer(this.cosmosAsyncContainer.getId()); Thread.sleep(1000); Instant beforeInitializingRntbdServiceEndpoint = Instant.now(); CosmosItemResponse<TestItem> operation1Response = container.upsertItem(testItem); Instant afterInitializingRntbdServiceEndpoint = Instant.now(); Thread.sleep(1000); Instant beforeOperation2 = Instant.now(); CosmosItemResponse<TestItem> operation2Response = container.upsertItem(testItem); Instant afterOperation2 = Instant.now(); Thread.sleep(1000); Instant beforeOperation3 = Instant.now(); CosmosItemResponse<TestItem> operation3Response = container.upsertItem(testItem); Instant afterOperation3 = Instant.now(); validateRntbdStatistics(operation3Response.getDiagnostics(), beforeClientInitialization, beforeInitializingRntbdServiceEndpoint, afterInitializingRntbdServiceEndpoint, beforeOperation2, afterOperation2, beforeOperation3, afterOperation3, connectionStateListenerEnabled); CosmosItemResponse<TestItem> readItemResponse = container.readItem(testItem.id, new PartitionKey(testItem.mypk), TestItem.class); validate(readItemResponse.getDiagnostics(), 0, ModelBridgeInternal.getPayloadLength(readItemResponse)); CosmosItemResponse<Object> deleteItemResponse = container.deleteItem(testItem, null); validate(deleteItemResponse.getDiagnostics(), 0, 0); } finally { LifeCycleUtils.closeQuietly(client1); } } private void validateRntbdStatistics(CosmosDiagnostics cosmosDiagnostics, Instant clientInitializationTime, Instant beforeInitializingRntbdServiceEndpoint, Instant afterInitializingRntbdServiceEndpoint, Instant beforeOperation2, Instant afterOperation2, Instant beforeOperation3, Instant afterOperation3, boolean connectionStateListenerEnabled) throws Exception { ObjectNode diagnostics = (ObjectNode) OBJECT_MAPPER.readTree(cosmosDiagnostics.toString()); JsonNode responseStatisticsList = diagnostics.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); assertThat(responseStatisticsList.size()).isGreaterThan(0); JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); assertThat(storeResult).isNotNull(); JsonNode replicaStatusList = storeResult.get("replicaStatusList"); assertThat(replicaStatusList.isArray()).isTrue(); assertThat(replicaStatusList.size()).isGreaterThan(0); JsonNode serviceEndpointStatistics = storeResult.get("serviceEndpointStatistics"); assertThat(serviceEndpointStatistics).isNotNull(); assertThat(serviceEndpointStatistics.get("availableChannels").asInt(-1)).isGreaterThan(0); assertThat(serviceEndpointStatistics.get("acquiredChannels").asInt(-1)).isEqualTo(0); assertThat(serviceEndpointStatistics.get("inflightRequests").asInt(-1)).isEqualTo(1); assertThat(serviceEndpointStatistics.get("isClosed").asBoolean()).isEqualTo(false); JsonNode channelStatistics = storeResult.get("channelStatistics"); assertThat(channelStatistics).isNotNull(); assertThat(channelStatistics.get("channelId").asText()).isNotEmpty(); assertThat(channelStatistics.get("channelTaskQueueSize").asInt(-1)).isGreaterThanOrEqualTo(0); assertThat(channelStatistics.get("pendingRequestsCount").asInt(-1)).isGreaterThanOrEqualTo(0); assertThat(channelStatistics.get("lastReadTime").asText()).isNotEmpty(); assertThat(channelStatistics.get("waitForConnectionInit").asText()).isNotEmpty(); JsonNode connectionStateListenerMetrics = serviceEndpointStatistics.get("cerMetrics"); if (connectionStateListenerEnabled) { assertThat(connectionStateListenerMetrics).isNotNull(); assertThat(connectionStateListenerMetrics.get("lastCallTimestamp")).isNull(); assertThat(connectionStateListenerMetrics.get("lastActionableContext")).isNull(); } else { assertThat(connectionStateListenerMetrics).isNull(); } Instant beforeInitializationThreshold = beforeInitializingRntbdServiceEndpoint.minusMillis(1); assertThat(Instant.parse(serviceEndpointStatistics.get("createdTime").asText())) .isAfterOrEqualTo(beforeInitializationThreshold); Instant afterInitializationThreshold = afterInitializingRntbdServiceEndpoint.plusMillis(2); assertThat(Instant.parse(serviceEndpointStatistics.get("createdTime").asText())) .isBeforeOrEqualTo(afterInitializationThreshold); Instant afterOperation2Threshold = afterOperation2.plusMillis(2); Instant beforeOperation2Threshold = beforeOperation2.minusMillis(2); assertThat(Instant.parse(serviceEndpointStatistics.get("lastRequestTime").asText())) .isAfterOrEqualTo(beforeOperation2Threshold.toString()) .isBeforeOrEqualTo(afterOperation2Threshold.toString()); assertThat(Instant.parse(serviceEndpointStatistics.get("lastSuccessfulRequestTime").asText())) .isAfterOrEqualTo(beforeOperation2Threshold.toString()) .isBeforeOrEqualTo(afterOperation2Threshold.toString()); } private void validate(CosmosDiagnostics cosmosDiagnostics, int expectedRequestPayloadSize, int expectedResponsePayloadSize) throws Exception { ObjectNode diagnostics = (ObjectNode) OBJECT_MAPPER.readTree(cosmosDiagnostics.toString()); JsonNode responseStatisticsList = diagnostics.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); assertThat(responseStatisticsList.size()).isGreaterThan(0); JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); boolean hasPayload = storeResult.get("exceptionMessage") == null; assertThat(storeResult).isNotNull(); assertThat(storeResult.get("rntbdRequestLengthInBytes").asInt(-1)).isGreaterThan(expectedRequestPayloadSize); assertThat(storeResult.get("rntbdRequestLengthInBytes").asInt(-1)).isGreaterThan(expectedRequestPayloadSize); assertThat(storeResult.get("requestPayloadLengthInBytes").asInt(-1)).isEqualTo(expectedRequestPayloadSize); if (hasPayload) { assertThat(storeResult.get("responsePayloadLengthInBytes").asInt(-1)).isEqualTo(expectedResponsePayloadSize); } assertThat(storeResult.get("rntbdResponseLengthInBytes").asInt(-1)).isGreaterThan(expectedResponsePayloadSize); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void addressResolutionStatistics() { CosmosClient client1 = null; CosmosClient client2 = null; String databaseId = DatabaseForTest.generateId(); String containerId = UUID.randomUUID().toString(); CosmosDatabase cosmosDatabase = null; CosmosContainer cosmosContainer = null; try { client1 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); client1.createDatabase(databaseId); cosmosDatabase = client1.getDatabase(databaseId); cosmosDatabase.createContainer(containerId, "/mypk"); InternalObjectNode internalObjectNode = getInternalObjectNode(); cosmosContainer = cosmosDatabase.getContainer(containerId); CosmosItemResponse<InternalObjectNode> writeResourceResponse = cosmosContainer.createItem(internalObjectNode); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("addressResolutionStatistics"); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("\"inflightRequest\":false"); assertThat(writeResourceResponse.getDiagnostics().toString()).doesNotContain("endTime=\"null\""); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("\"exceptionMessage\":null"); client2 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); cosmosDatabase = client2.getDatabase(databaseId); cosmosContainer = cosmosDatabase.getContainer(containerId); AsyncDocumentClient asyncDocumentClient = client2.asyncClient().getContextClient(); GlobalAddressResolver addressResolver = (GlobalAddressResolver) FieldUtils.readField(asyncDocumentClient, "addressResolver", true); @SuppressWarnings("rawtypes") Map addressCacheByEndpoint = (Map) FieldUtils.readField(addressResolver, "addressCacheByEndpoint", true); Object endpointCache = addressCacheByEndpoint.values().toArray()[0]; GatewayAddressCache addressCache = (GatewayAddressCache) FieldUtils.readField(endpointCache, "addressCache", true); HttpClient httpClient = httpClient(true); FieldUtils.writeField(addressCache, "httpClient", httpClient, true); new Thread(() -> { try { Thread.sleep(5000); HttpClient httpClient1 = httpClient(false); FieldUtils.writeField(addressCache, "httpClient", httpClient1, true); } catch (Exception e) { fail(e.getMessage()); } }).start(); PartitionKey partitionKey = new PartitionKey(internalObjectNode.get("mypk")); CosmosItemResponse<InternalObjectNode> readResourceResponse = cosmosContainer.readItem(internalObjectNode.getId(), partitionKey, new CosmosItemRequestOptions(), InternalObjectNode.class); assertThat(readResourceResponse.getDiagnostics().toString()).contains("addressResolutionStatistics"); assertThat(readResourceResponse.getDiagnostics().toString()).contains("\"inflightRequest\":false"); assertThat(readResourceResponse.getDiagnostics().toString()).doesNotContain("endTime=\"null\""); assertThat(readResourceResponse.getDiagnostics().toString()).contains("\"exceptionMessage\":\"io.netty" + ".channel.AbstractChannel$AnnotatedConnectException: Connection refused"); } catch (Exception ex) { logger.error("Error in test addressResolutionStatistics", ex); fail("This test should not throw exception " + ex); } finally { safeDeleteSyncDatabase(cosmosDatabase); if (client1 != null) { client1.close(); } if (client2 != null) { client2.close(); } } } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void responseStatisticRequestStartTimeUTCForDirectCall() { CosmosAsyncClient client = null; String databaseId = DatabaseForTest.generateId(); FaultInjectionRule faultInjectionRule = null; try { client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(TestConfigurations.HOST) .endToEndOperationLatencyPolicyConfig( new CosmosEndToEndOperationLatencyPolicyConfigBuilder(Duration.ofSeconds(2)).build() ).buildAsyncClient(); createDatabase(client, databaseId); CosmosAsyncContainer container = createCollection(client, databaseId, getCollectionDefinition()); TestItem testItem = TestItem.createNewItem(); container.createItem(testItem).block(); faultInjectionRule = new FaultInjectionRuleBuilder("PARTITION_IS_MIGRATING") .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.CREATE_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.PARTITION_IS_MIGRATING) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(faultInjectionRule)).block(); CosmosDiagnostics cosmosDiagnostics = null; try { cosmosDiagnostics = container.createItem(TestItem.createNewItem()) .block() .getDiagnostics(); } catch (Exception exception) { fail("Request should succeeded, but failed with " + exception); } List<ClientSideRequestStatistics> clientSideRequestStatistics = (List<ClientSideRequestStatistics>) cosmosDiagnostics.getClientSideRequestStatistics(); List<ClientSideRequestStatistics.StoreResponseStatistics> responseStatistic = clientSideRequestStatistics.get(0).getResponseStatisticsList(); assert responseStatistic.size() == 2; Instant firstRequestStartTime = responseStatistic.get(0).getRequestStartTimeUTC(); Instant secondRequestStartTime = responseStatistic.get(1).getRequestStartTimeUTC(); assert firstRequestStartTime != null && secondRequestStartTime != null; assert firstRequestStartTime != secondRequestStartTime; assert firstRequestStartTime.compareTo(secondRequestStartTime) < 0; } finally { if (faultInjectionRule != null) { faultInjectionRule.disable(); } safeClose(client); } } private InternalObjectNode getInternalObjectNode() { InternalObjectNode internalObjectNode = new InternalObjectNode(); String uuid = UUID.randomUUID().toString(); internalObjectNode.setId(uuid); BridgeInternal.setProperty(internalObjectNode, "mypk", uuid); return internalObjectNode; } private InternalObjectNode getInternalObjectNode(String pkValue) { InternalObjectNode internalObjectNode = new InternalObjectNode(); String uuid = UUID.randomUUID().toString(); internalObjectNode.setId(uuid); BridgeInternal.setProperty(internalObjectNode, "mypk", pkValue); return internalObjectNode; } private List<ClientSideRequestStatistics.StoreResponseStatistics> getStoreResponseStatistics(ClientSideRequestStatistics requestStatistics) throws Exception { Field storeResponseStatisticsField = ClientSideRequestStatistics.class.getDeclaredField("supplementalResponseStatisticsList"); storeResponseStatisticsField.setAccessible(true); @SuppressWarnings({"unchecked"}) List<ClientSideRequestStatistics.StoreResponseStatistics> list = (List<ClientSideRequestStatistics.StoreResponseStatistics>) storeResponseStatisticsField.get(requestStatistics); return list; } private void clearStoreResponseStatistics(ClientSideRequestStatistics requestStatistics) throws Exception { Field storeResponseStatisticsField = ClientSideRequestStatistics.class.getDeclaredField("supplementalResponseStatisticsList"); storeResponseStatisticsField.setAccessible(true); storeResponseStatisticsField.set(requestStatistics, new ArrayList<ClientSideRequestStatistics.StoreResponseStatistics>()); } private void validateTransportRequestTimelineGateway(String diagnostics) { assertThat(diagnostics).contains("\"eventName\":\"connectionConfigured\""); assertThat(diagnostics).contains("\"eventName\":\"requestSent\""); assertThat(diagnostics).contains("\"eventName\":\"transitTime\""); assertThat(diagnostics).contains("\"eventName\":\"received\""); } private void validateTransportRequestTimelineDirect(String diagnostics) { assertThat(diagnostics).contains("\"eventName\":\"created\""); assertThat(diagnostics).contains("\"eventName\":\"queued\""); assertThat(diagnostics).contains("\"eventName\":\"channelAcquisitionStarted\""); assertThat(diagnostics).contains("\"eventName\":\"pipelined\""); assertThat(diagnostics).contains("\"eventName\":\"transitTime\""); assertThat(diagnostics).contains("\"eventName\":\"decodeTime"); assertThat(diagnostics).contains("\"eventName\":\"received\""); assertThat(diagnostics).contains("\"eventName\":\"completed\""); assertThat(diagnostics).contains("\"startTimeUTC\""); assertThat(diagnostics).contains("\"durationInMilliSecs\""); } public void isValidJSON(final String json) { try { final JsonParser parser = new JsonFactory().createParser(json); while (parser.nextToken() != null) { } } catch (IOException ex) { fail("Diagnostic string is not in json format ", ex); } } private HttpClient httpClient(boolean fakeProxy) { HttpClientConfig httpClientConfig; if(fakeProxy) { httpClientConfig = new HttpClientConfig(new Configs()) .withProxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 8888))); } else { httpClientConfig = new HttpClientConfig(new Configs()); } return HttpClient.createFixed(httpClientConfig); } private IndexUtilizationInfo createFromJSONString(String jsonString) { ObjectMapper indexUtilizationInfoObjectMapper = new ObjectMapper(); IndexUtilizationInfo indexUtilizationInfo = null; try { indexUtilizationInfo = indexUtilizationInfoObjectMapper.readValue(jsonString, IndexUtilizationInfo.class); } catch (JsonProcessingException e) { logger.error("Json not correctly formed ", e); } return indexUtilizationInfo; } private void validateRegionContacted(CosmosDiagnostics cosmosDiagnostics, CosmosAsyncClient cosmosAsyncClient) throws Exception { RxDocumentClientImpl rxDocumentClient = (RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(cosmosAsyncClient); GlobalEndpointManager globalEndpointManager = ReflectionUtils.getGlobalEndpointManager(rxDocumentClient); LocationCache locationCache = ReflectionUtils.getLocationCache(globalEndpointManager); Field locationInfoField = LocationCache.class.getDeclaredField("locationInfo"); locationInfoField.setAccessible(true); Object locationInfo = locationInfoField.get(locationCache); Class<?> DatabaseAccountLocationsInfoClass = Class.forName("com.azure.cosmos.implementation.routing" + ".LocationCache$DatabaseAccountLocationsInfo"); Field availableWriteEndpointByLocation = DatabaseAccountLocationsInfoClass.getDeclaredField( "availableWriteEndpointByLocation"); availableWriteEndpointByLocation.setAccessible(true); @SuppressWarnings("unchecked") Map<String, URI> map = (Map<String, URI>) availableWriteEndpointByLocation.get(locationInfo); String regionName = map.keySet().iterator().next(); assertThat(cosmosDiagnostics.getContactedRegionNames().size()).isEqualTo(1); assertThat(cosmosDiagnostics.getContactedRegionNames().iterator().next()).isEqualTo(regionName.toLowerCase()); } private void validateChannelStatistics(CosmosDiagnostics cosmosDiagnostics) { for (ClientSideRequestStatistics clientSideRequestStatistics : cosmosDiagnostics.getClientSideRequestStatistics()) { for (ClientSideRequestStatistics.StoreResponseStatistics storeResponseStatistics : clientSideRequestStatistics.getResponseStatisticsList()) { assertThat(storeResponseStatistics).isNotNull(); RntbdChannelStatistics rntbdChannelStatistics = storeResponseStatistics .getStoreResult() .getStoreResponseDiagnostics() .getRntbdChannelStatistics(); assertThat(rntbdChannelStatistics).isNotNull(); try { String rntbdChannelStatisticsString = Utils.getSimpleObjectMapper().writeValueAsString(rntbdChannelStatistics); assertThat(rntbdChannelStatisticsString).contains("\"channelId\":\"" + rntbdChannelStatistics.getChannelId() + "\""); assertThat(rntbdChannelStatisticsString) .contains("\"channelTaskQueueSize\":" + rntbdChannelStatistics.getChannelTaskQueueSize()); assertThat(rntbdChannelStatisticsString) .contains("\"pendingRequestsCount\":" + rntbdChannelStatistics.getPendingRequestsCount()); assertThat(rntbdChannelStatisticsString) .contains("\"lastReadTime\":\"" + rntbdChannelStatistics.getLastReadTime() + "\""); if (rntbdChannelStatistics.getTransitTimeoutCount() > 0) { assertThat(rntbdChannelStatisticsString) .contains("\"transitTimeoutCount\":" + rntbdChannelStatistics.getTransitTimeoutCount()); assertThat(rntbdChannelStatisticsString) .contains("\"transitTimeoutStartingTime\":\"" + rntbdChannelStatistics.getTransitTimeoutStartingTime() + "\""); } else { assertThat(rntbdChannelStatisticsString) .doesNotContain("\"transitTimeoutCount\":" + rntbdChannelStatistics.getTransitTimeoutCount()); assertThat(rntbdChannelStatisticsString) .doesNotContain("\"transitTimeoutStartingTime\":\"" + rntbdChannelStatistics.getTransitTimeoutStartingTime() + "\""); } assertThat(rntbdChannelStatisticsString).contains("\"waitForConnectionInit\":" + rntbdChannelStatistics.isWaitForConnectionInit()); } catch (JsonProcessingException e) { fail("Failed to parse RntbdChannelStatistics"); } } } } private CosmosDiagnostics performDocumentOperation( CosmosAsyncContainer cosmosAsyncContainer, OperationType operationType, TestItem createdItem) { if (operationType == OperationType.Query) { String query = "SELECT * from c"; FeedResponse<TestItem> itemFeedResponse = cosmosAsyncContainer.queryItems(query, TestItem.class).byPage().blockFirst(); return itemFeedResponse.getCosmosDiagnostics(); } if (operationType == OperationType.Read) { return cosmosAsyncContainer .readItem(createdItem.id, new PartitionKey(createdItem.mypk), TestItem.class) .block() .getDiagnostics(); } if (operationType == OperationType.Replace) { return cosmosAsyncContainer .replaceItem(createdItem, createdItem.id, new PartitionKey(createdItem.mypk)) .block() .getDiagnostics(); } if (operationType == OperationType.Create) { return cosmosAsyncContainer.createItem(TestItem.createNewItem()).block().getDiagnostics(); } throw new IllegalArgumentException("The operation type is not supported"); } public static class TestItem { public String id; public String mypk; public TestItem() { } public TestItem(String id, String mypk) { this.id = id; this.mypk = mypk; } public static TestItem createNewItem() { return new TestItem(UUID.randomUUID().toString(), UUID.randomUUID().toString()); } } }
```suggestion new MockTokenCredential(); ```
private SchemaRegistryAsyncClient getSchemaRegistryClient() { final String resourceName = "/compat/" + testInfo.getTestMethod().get().getName() + ".json"; final RecordedData recordedData; try (InputStream stream = SchemaRegistryApacheAvroSerializerTest.class.getResourceAsStream(resourceName)) { recordedData = SERIALIZER.deserialize(stream, RecordedData.class, SerializerEncoding.JSON); } catch (IOException e) { throw new UncheckedIOException("Unable to get resource input stream for: " + resourceName, e); } final TokenCredential tokenCredential = mock(TokenCredential.class); when(tokenCredential.getToken(any(TokenRequestContext.class))) .thenAnswer(invocationOnMock -> Mono.fromCallable(() -> new AccessToken("foo", OffsetDateTime.now().plusMinutes(20)))); final HttpClient mockedHttpClient = setupHttpClient(recordedData); final SchemaRegistryClientBuilder builder = new SchemaRegistryClientBuilder() .credential(tokenCredential) .pipeline(new HttpPipelineBuilder().httpClient(mockedHttpClient).build()) .fullyQualifiedNamespace(PLAYBACK_ENDPOINT); return builder.buildAsyncClient(); }
new AccessToken("foo", OffsetDateTime.now().plusMinutes(20))));
private SchemaRegistryAsyncClient getSchemaRegistryClient() { final String resourceName = "/compat/" + testInfo.getTestMethod().get().getName() + ".json"; final RecordedData recordedData; try (InputStream stream = SchemaRegistryApacheAvroSerializerTest.class.getResourceAsStream(resourceName)) { recordedData = SERIALIZER.deserialize(stream, RecordedData.class, SerializerEncoding.JSON); } catch (IOException e) { throw new UncheckedIOException("Unable to get resource input stream for: " + resourceName, e); } final TokenCredential tokenCredential = mock(TokenCredential.class); when(tokenCredential.getToken(any(TokenRequestContext.class))) .thenAnswer(invocationOnMock -> Mono.fromCallable(() -> new AccessToken("foo", OffsetDateTime.now().plusMinutes(20)))); final HttpClient mockedHttpClient = setupHttpClient(recordedData); final SchemaRegistryClientBuilder builder = new SchemaRegistryClientBuilder() .credential(tokenCredential) .pipeline(new HttpPipelineBuilder().httpClient(mockedHttpClient).build()) .fullyQualifiedNamespace(PLAYBACK_ENDPOINT); return builder.buildAsyncClient(); }
class does not have an no-args * constructor. */ @Test public void throwsWhenConstructorNotAvailable() { final AvroSerializer avroSerializer = new AvroSerializer(false, ENCODER_FACTORY, DECODER_FACTORY); final SerializerOptions serializerOptions = new SerializerOptions(MOCK_SCHEMA_GROUP, true, MOCK_CACHE_SIZE); final SchemaRegistryApacheAvroSerializer serializer = new SchemaRegistryApacheAvroSerializer( client, avroSerializer, serializerOptions); final PlayingCard playingCard = new PlayingCard(true, 10, PlayingCardSuit.DIAMONDS); final TypeReference<InvalidMessage> typeReference = TypeReference.createInstance(InvalidMessage.class); StepVerifier.create(serializer.serializeAsync(playingCard, typeReference)) .expectError(IllegalArgumentException.class) .verify(); }
class does not have an no-args * constructor. */ @Test public void throwsWhenConstructorNotAvailable() { final AvroSerializer avroSerializer = new AvroSerializer(false, ENCODER_FACTORY, DECODER_FACTORY); final SerializerOptions serializerOptions = new SerializerOptions(MOCK_SCHEMA_GROUP, true, MOCK_CACHE_SIZE); final SchemaRegistryApacheAvroSerializer serializer = new SchemaRegistryApacheAvroSerializer( client, avroSerializer, serializerOptions); final PlayingCard playingCard = new PlayingCard(true, 10, PlayingCardSuit.DIAMONDS); final TypeReference<InvalidMessage> typeReference = TypeReference.createInstance(InvalidMessage.class); StepVerifier.create(serializer.serializeAsync(playingCard, typeReference)) .expectError(IllegalArgumentException.class) .verify(); }
This and the sync try/catch are potentially mapping different exception types. `onErrorMap` defaults to mapping all `Throwable`s, we should look into using the overload method `onErrorMap(Class<? extends Throwable>, Function)`.
public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithAzureCli(request) .doOnNext(token -> LoggingUtil.logTokenSuccess(LOGGER, request)) .doOnError(error -> LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, error)) .onErrorMap(error -> new CredentialUnavailableException("Azure CLI authentication is not available", error)); }
.onErrorMap(error -> new CredentialUnavailableException("Azure CLI authentication is not available", error));
public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithAzureCli(request) .doOnNext(token -> LoggingUtil.logTokenSuccess(LOGGER, request)) .doOnError(error -> LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, error)) .onErrorMap(error -> { if (identityClient.getIdentityClientOptions().isChained()) { return new CredentialUnavailableException(error.getMessage(), error); } else { return error; } }); }
class AzureCliCredential implements TokenCredential { private static final ClientLogger LOGGER = new ClientLogger(AzureCliCredential.class); private final IdentityClient identityClient; private final IdentitySyncClient identitySyncClient; /** * Creates an AzureCliSecretCredential with default identity client options. * @param tenantId the tenant id of the application * @param identityClientOptions the options to configure the identity client */ AzureCliCredential(String tenantId, IdentityClientOptions identityClientOptions) { IdentityClientBuilder builder = new IdentityClientBuilder() .tenantId(tenantId) .identityClientOptions(identityClientOptions); identityClient = builder.build(); identitySyncClient = builder.buildSyncClient(); } @Override @Override public AccessToken getTokenSync(TokenRequestContext request) { try { AccessToken accessToken = identitySyncClient.authenticateWithAzureCli(request); LoggingUtil.logTokenSuccess(LOGGER, request); return accessToken; } catch (Exception e) { LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, e); throw new CredentialUnavailableException("Azure CLI authentication is not available", e); } } }
class AzureCliCredential implements TokenCredential { private static final ClientLogger LOGGER = new ClientLogger(AzureCliCredential.class); private final IdentityClient identityClient; private final IdentitySyncClient identitySyncClient; /** * Creates an AzureCliSecretCredential with default identity client options. * @param tenantId the tenant id of the application * @param identityClientOptions the options to configure the identity client */ AzureCliCredential(String tenantId, IdentityClientOptions identityClientOptions) { IdentityClientBuilder builder = new IdentityClientBuilder() .tenantId(tenantId) .identityClientOptions(identityClientOptions); identityClient = builder.build(); identitySyncClient = builder.buildSyncClient(); } @Override @Override public AccessToken getTokenSync(TokenRequestContext request) { try { AccessToken accessToken = identitySyncClient.authenticateWithAzureCli(request); LoggingUtil.logTokenSuccess(LOGGER, request); return accessToken; } catch (Exception e) { LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, e); if (identityClient.getIdentityClientOptions().isChained()) { throw new CredentialUnavailableException(e.getMessage(), e); } else { throw e; } } } }
So, we're changing the type thrown here in all cases. Should we add internal methods to know when we're using this as part of chaining to properly handle continuation on a credential not being usable and in other public API cases we retain current functionality? Also, do we unwrap this wrapped exception when we hit the end of chaining to throw the appropriate exception to maintain backwards compatibility? Ex, if before I was catching an MSAL exception type when the chain failed to retry in my own application's logic that catch block won't be triggered anymore as the exception type has changed to `CredentialUnavailableException`. One last thought, do we need more logic here to differentiate between a credential being unavailable and a true exception being thrown, like an `IOException` because of a networking failure?
public AccessToken getTokenSync(TokenRequestContext request) { try { AccessToken accessToken = identitySyncClient.authenticateWithAzureCli(request); LoggingUtil.logTokenSuccess(LOGGER, request); return accessToken; } catch (Exception e) { LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, e); throw new CredentialUnavailableException("Azure CLI authentication is not available", e); } }
throw new CredentialUnavailableException("Azure CLI authentication is not available", e);
public AccessToken getTokenSync(TokenRequestContext request) { try { AccessToken accessToken = identitySyncClient.authenticateWithAzureCli(request); LoggingUtil.logTokenSuccess(LOGGER, request); return accessToken; } catch (Exception e) { LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, e); if (identityClient.getIdentityClientOptions().isChained()) { throw new CredentialUnavailableException(e.getMessage(), e); } else { throw e; } } }
class AzureCliCredential implements TokenCredential { private static final ClientLogger LOGGER = new ClientLogger(AzureCliCredential.class); private final IdentityClient identityClient; private final IdentitySyncClient identitySyncClient; /** * Creates an AzureCliSecretCredential with default identity client options. * @param tenantId the tenant id of the application * @param identityClientOptions the options to configure the identity client */ AzureCliCredential(String tenantId, IdentityClientOptions identityClientOptions) { IdentityClientBuilder builder = new IdentityClientBuilder() .tenantId(tenantId) .identityClientOptions(identityClientOptions); identityClient = builder.build(); identitySyncClient = builder.buildSyncClient(); } @Override public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithAzureCli(request) .doOnNext(token -> LoggingUtil.logTokenSuccess(LOGGER, request)) .doOnError(error -> LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, error)) .onErrorMap(error -> new CredentialUnavailableException("Azure CLI authentication is not available", error)); } @Override }
class AzureCliCredential implements TokenCredential { private static final ClientLogger LOGGER = new ClientLogger(AzureCliCredential.class); private final IdentityClient identityClient; private final IdentitySyncClient identitySyncClient; /** * Creates an AzureCliSecretCredential with default identity client options. * @param tenantId the tenant id of the application * @param identityClientOptions the options to configure the identity client */ AzureCliCredential(String tenantId, IdentityClientOptions identityClientOptions) { IdentityClientBuilder builder = new IdentityClientBuilder() .tenantId(tenantId) .identityClientOptions(identityClientOptions); identityClient = builder.build(); identitySyncClient = builder.buildSyncClient(); } @Override public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithAzureCli(request) .doOnNext(token -> LoggingUtil.logTokenSuccess(LOGGER, request)) .doOnError(error -> LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, error)) .onErrorMap(error -> { if (identityClient.getIdentityClientOptions().isChained()) { return new CredentialUnavailableException(error.getMessage(), error); } else { return error; } }); } @Override }
Hm, good point. I'll rework this.
public AccessToken getTokenSync(TokenRequestContext request) { try { AccessToken accessToken = identitySyncClient.authenticateWithAzureCli(request); LoggingUtil.logTokenSuccess(LOGGER, request); return accessToken; } catch (Exception e) { LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, e); throw new CredentialUnavailableException("Azure CLI authentication is not available", e); } }
throw new CredentialUnavailableException("Azure CLI authentication is not available", e);
public AccessToken getTokenSync(TokenRequestContext request) { try { AccessToken accessToken = identitySyncClient.authenticateWithAzureCli(request); LoggingUtil.logTokenSuccess(LOGGER, request); return accessToken; } catch (Exception e) { LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, e); if (identityClient.getIdentityClientOptions().isChained()) { throw new CredentialUnavailableException(e.getMessage(), e); } else { throw e; } } }
class AzureCliCredential implements TokenCredential { private static final ClientLogger LOGGER = new ClientLogger(AzureCliCredential.class); private final IdentityClient identityClient; private final IdentitySyncClient identitySyncClient; /** * Creates an AzureCliSecretCredential with default identity client options. * @param tenantId the tenant id of the application * @param identityClientOptions the options to configure the identity client */ AzureCliCredential(String tenantId, IdentityClientOptions identityClientOptions) { IdentityClientBuilder builder = new IdentityClientBuilder() .tenantId(tenantId) .identityClientOptions(identityClientOptions); identityClient = builder.build(); identitySyncClient = builder.buildSyncClient(); } @Override public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithAzureCli(request) .doOnNext(token -> LoggingUtil.logTokenSuccess(LOGGER, request)) .doOnError(error -> LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, error)) .onErrorMap(error -> new CredentialUnavailableException("Azure CLI authentication is not available", error)); } @Override }
class AzureCliCredential implements TokenCredential { private static final ClientLogger LOGGER = new ClientLogger(AzureCliCredential.class); private final IdentityClient identityClient; private final IdentitySyncClient identitySyncClient; /** * Creates an AzureCliSecretCredential with default identity client options. * @param tenantId the tenant id of the application * @param identityClientOptions the options to configure the identity client */ AzureCliCredential(String tenantId, IdentityClientOptions identityClientOptions) { IdentityClientBuilder builder = new IdentityClientBuilder() .tenantId(tenantId) .identityClientOptions(identityClientOptions); identityClient = builder.build(); identitySyncClient = builder.buildSyncClient(); } @Override public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithAzureCli(request) .doOnNext(token -> LoggingUtil.logTokenSuccess(LOGGER, request)) .doOnError(error -> LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, error)) .onErrorMap(error -> { if (identityClient.getIdentityClientOptions().isChained()) { return new CredentialUnavailableException(error.getMessage(), error); } else { return error; } }); } @Override }
I've updated it. We change nothing when you're using the credentials directly. We're not doing the re-throw as you suggested, but I'm okay with that. We're sharing the message out of the original exception as well as linking it as the cause. The stack will be right since we're just wrapping the exception we caught in the same method. Lemme know if you have further concerns. Thanks!
public AccessToken getTokenSync(TokenRequestContext request) { try { AccessToken accessToken = identitySyncClient.authenticateWithAzureCli(request); LoggingUtil.logTokenSuccess(LOGGER, request); return accessToken; } catch (Exception e) { LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, e); throw new CredentialUnavailableException("Azure CLI authentication is not available", e); } }
throw new CredentialUnavailableException("Azure CLI authentication is not available", e);
public AccessToken getTokenSync(TokenRequestContext request) { try { AccessToken accessToken = identitySyncClient.authenticateWithAzureCli(request); LoggingUtil.logTokenSuccess(LOGGER, request); return accessToken; } catch (Exception e) { LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, e); if (identityClient.getIdentityClientOptions().isChained()) { throw new CredentialUnavailableException(e.getMessage(), e); } else { throw e; } } }
class AzureCliCredential implements TokenCredential { private static final ClientLogger LOGGER = new ClientLogger(AzureCliCredential.class); private final IdentityClient identityClient; private final IdentitySyncClient identitySyncClient; /** * Creates an AzureCliSecretCredential with default identity client options. * @param tenantId the tenant id of the application * @param identityClientOptions the options to configure the identity client */ AzureCliCredential(String tenantId, IdentityClientOptions identityClientOptions) { IdentityClientBuilder builder = new IdentityClientBuilder() .tenantId(tenantId) .identityClientOptions(identityClientOptions); identityClient = builder.build(); identitySyncClient = builder.buildSyncClient(); } @Override public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithAzureCli(request) .doOnNext(token -> LoggingUtil.logTokenSuccess(LOGGER, request)) .doOnError(error -> LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, error)) .onErrorMap(error -> new CredentialUnavailableException("Azure CLI authentication is not available", error)); } @Override }
class AzureCliCredential implements TokenCredential { private static final ClientLogger LOGGER = new ClientLogger(AzureCliCredential.class); private final IdentityClient identityClient; private final IdentitySyncClient identitySyncClient; /** * Creates an AzureCliSecretCredential with default identity client options. * @param tenantId the tenant id of the application * @param identityClientOptions the options to configure the identity client */ AzureCliCredential(String tenantId, IdentityClientOptions identityClientOptions) { IdentityClientBuilder builder = new IdentityClientBuilder() .tenantId(tenantId) .identityClientOptions(identityClientOptions); identityClient = builder.build(); identitySyncClient = builder.buildSyncClient(); } @Override public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithAzureCli(request) .doOnNext(token -> LoggingUtil.logTokenSuccess(LOGGER, request)) .doOnError(error -> LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, error)) .onErrorMap(error -> { if (identityClient.getIdentityClientOptions().isChained()) { return new CredentialUnavailableException(error.getMessage(), error); } else { return error; } }); } @Override }
I think we have two options. 1. Update the individual credential and if it is called from DAC/chain, we raise `CredentialUnavailableException` 2. We can maintain a list of "dev credentials" in DAC and catch `ClientAuthenticationException` and continue in DAC.
public AccessToken getTokenSync(TokenRequestContext request) { try { AccessToken accessToken = identitySyncClient.authenticateWithAzureCli(request); LoggingUtil.logTokenSuccess(LOGGER, request); return accessToken; } catch (Exception e) { LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, e); throw new CredentialUnavailableException("Azure CLI authentication is not available", e); } }
throw new CredentialUnavailableException("Azure CLI authentication is not available", e);
public AccessToken getTokenSync(TokenRequestContext request) { try { AccessToken accessToken = identitySyncClient.authenticateWithAzureCli(request); LoggingUtil.logTokenSuccess(LOGGER, request); return accessToken; } catch (Exception e) { LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, e); if (identityClient.getIdentityClientOptions().isChained()) { throw new CredentialUnavailableException(e.getMessage(), e); } else { throw e; } } }
class AzureCliCredential implements TokenCredential { private static final ClientLogger LOGGER = new ClientLogger(AzureCliCredential.class); private final IdentityClient identityClient; private final IdentitySyncClient identitySyncClient; /** * Creates an AzureCliSecretCredential with default identity client options. * @param tenantId the tenant id of the application * @param identityClientOptions the options to configure the identity client */ AzureCliCredential(String tenantId, IdentityClientOptions identityClientOptions) { IdentityClientBuilder builder = new IdentityClientBuilder() .tenantId(tenantId) .identityClientOptions(identityClientOptions); identityClient = builder.build(); identitySyncClient = builder.buildSyncClient(); } @Override public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithAzureCli(request) .doOnNext(token -> LoggingUtil.logTokenSuccess(LOGGER, request)) .doOnError(error -> LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, error)) .onErrorMap(error -> new CredentialUnavailableException("Azure CLI authentication is not available", error)); } @Override }
class AzureCliCredential implements TokenCredential { private static final ClientLogger LOGGER = new ClientLogger(AzureCliCredential.class); private final IdentityClient identityClient; private final IdentitySyncClient identitySyncClient; /** * Creates an AzureCliSecretCredential with default identity client options. * @param tenantId the tenant id of the application * @param identityClientOptions the options to configure the identity client */ AzureCliCredential(String tenantId, IdentityClientOptions identityClientOptions) { IdentityClientBuilder builder = new IdentityClientBuilder() .tenantId(tenantId) .identityClientOptions(identityClientOptions); identityClient = builder.build(); identitySyncClient = builder.buildSyncClient(); } @Override public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithAzureCli(request) .doOnNext(token -> LoggingUtil.logTokenSuccess(LOGGER, request)) .doOnError(error -> LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, error)) .onErrorMap(error -> { if (identityClient.getIdentityClientOptions().isChained()) { return new CredentialUnavailableException(error.getMessage(), error); } else { return error; } }); } @Override }
We are doing the first.
public AccessToken getTokenSync(TokenRequestContext request) { try { AccessToken accessToken = identitySyncClient.authenticateWithAzureCli(request); LoggingUtil.logTokenSuccess(LOGGER, request); return accessToken; } catch (Exception e) { LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, e); throw new CredentialUnavailableException("Azure CLI authentication is not available", e); } }
throw new CredentialUnavailableException("Azure CLI authentication is not available", e);
public AccessToken getTokenSync(TokenRequestContext request) { try { AccessToken accessToken = identitySyncClient.authenticateWithAzureCli(request); LoggingUtil.logTokenSuccess(LOGGER, request); return accessToken; } catch (Exception e) { LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, e); if (identityClient.getIdentityClientOptions().isChained()) { throw new CredentialUnavailableException(e.getMessage(), e); } else { throw e; } } }
class AzureCliCredential implements TokenCredential { private static final ClientLogger LOGGER = new ClientLogger(AzureCliCredential.class); private final IdentityClient identityClient; private final IdentitySyncClient identitySyncClient; /** * Creates an AzureCliSecretCredential with default identity client options. * @param tenantId the tenant id of the application * @param identityClientOptions the options to configure the identity client */ AzureCliCredential(String tenantId, IdentityClientOptions identityClientOptions) { IdentityClientBuilder builder = new IdentityClientBuilder() .tenantId(tenantId) .identityClientOptions(identityClientOptions); identityClient = builder.build(); identitySyncClient = builder.buildSyncClient(); } @Override public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithAzureCli(request) .doOnNext(token -> LoggingUtil.logTokenSuccess(LOGGER, request)) .doOnError(error -> LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, error)) .onErrorMap(error -> new CredentialUnavailableException("Azure CLI authentication is not available", error)); } @Override }
class AzureCliCredential implements TokenCredential { private static final ClientLogger LOGGER = new ClientLogger(AzureCliCredential.class); private final IdentityClient identityClient; private final IdentitySyncClient identitySyncClient; /** * Creates an AzureCliSecretCredential with default identity client options. * @param tenantId the tenant id of the application * @param identityClientOptions the options to configure the identity client */ AzureCliCredential(String tenantId, IdentityClientOptions identityClientOptions) { IdentityClientBuilder builder = new IdentityClientBuilder() .tenantId(tenantId) .identityClientOptions(identityClientOptions); identityClient = builder.build(); identitySyncClient = builder.buildSyncClient(); } @Override public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithAzureCli(request) .doOnNext(token -> LoggingUtil.logTokenSuccess(LOGGER, request)) .doOnError(error -> LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, error)) .onErrorMap(error -> { if (identityClient.getIdentityClientOptions().isChained()) { return new CredentialUnavailableException(error.getMessage(), error); } else { return error; } }); } @Override }
Session Receiver instance (ServiceBusReceiverAsyncClient) that we return via the public API _acceptNextSession_ will always be associated with a "single" session, so we can mock the public method `renewSessionLock()` that works with the associated session. (Note: ServiceBusReceiverAsyncClient that works with "multi"-session is internal, and we don't use (or have a dependency on) package internal APIs of ServiceBusReceiverAsyncClient that takes sessionId.)
void errorSourceOnSessionLock() { when(managementNode.renewSessionLock(SESSION_ID, null)).thenReturn(Mono.error(new AzureException("some error occurred."))); final ReceiverOptions receiverOptions = createNamedSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, true, SESSION_ID); final ServiceBusReceiverAsyncClient sessionReceiver2 = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, receiverOptions, connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, mock(ServiceBusSessionManager.class)); StepVerifier.create(sessionReceiver2.renewSessionLock()) .verifyErrorSatisfies(throwable -> { Assertions.assertTrue(throwable instanceof ServiceBusException); final ServiceBusErrorSource actual = ((ServiceBusException) throwable).getErrorSource(); Assertions.assertEquals(ServiceBusErrorSource.RENEW_LOCK, actual); }); }
StepVerifier.create(sessionReceiver2.renewSessionLock())
void errorSourceOnSessionLock() { when(managementNode.renewSessionLock(SESSION_ID, null)).thenReturn(Mono.error(new AzureException("some error occurred."))); final ReceiverOptions receiverOptions = createNamedSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, true, SESSION_ID); final ServiceBusReceiverAsyncClient sessionReceiver2 = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, receiverOptions, connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, mock(ServiceBusSessionManager.class)); StepVerifier.create(sessionReceiver2.renewSessionLock()) .verifyErrorSatisfies(throwable -> { Assertions.assertTrue(throwable instanceof ServiceBusException); final ServiceBusErrorSource actual = ((ServiceBusException) throwable).getErrorSource(); Assertions.assertEquals(ServiceBusErrorSource.RENEW_LOCK, actual); }); }
class ServiceBusReceiverAsyncClientTest { private static final ClientOptions CLIENT_OPTIONS = new ClientOptions(); private static final String PAYLOAD = "hello"; private static final byte[] PAYLOAD_BYTES = PAYLOAD.getBytes(UTF_8); private static final int PREFETCH = 5; private static final String NAMESPACE = "my-namespace-foo.net"; private static final String ENTITY_PATH = "queue-name"; private static final String SUBSCRIPTION_NAME = "subscription-name"; private static final MessagingEntityType ENTITY_TYPE = MessagingEntityType.QUEUE; private static final String NAMESPACE_CONNECTION_STRING = String.format( "Endpoint=sb: NAMESPACE, "some-name", "something-else"); private static final Duration CLEANUP_INTERVAL = Duration.ofSeconds(10); private static final String SESSION_ID = "my-session-id"; private static final String CLIENT_IDENTIFIER = "my-client-identifier"; private static final ClientLogger LOGGER = new ClientLogger(ServiceBusReceiverAsyncClientTest.class); private static final ServiceBusTracer NOOP_TRACER = new ServiceBusTracer(null, NAMESPACE, ENTITY_PATH); private final String messageTrackingUUID = UUID.randomUUID().toString(); private final ReplayProcessor<AmqpEndpointState> endpointProcessor = ReplayProcessor.cacheLast(); private final FluxSink<AmqpEndpointState> endpointSink = endpointProcessor.sink(FluxSink.OverflowStrategy.BUFFER); private final DirectProcessor<Message> messageProcessor = DirectProcessor.create(); private final FluxSink<Message> messageSink = messageProcessor.sink(FluxSink.OverflowStrategy.BUFFER); private ServiceBusConnectionProcessor connectionProcessor; private ServiceBusReceiverAsyncClient receiver; private ServiceBusReceiverAsyncClient sessionReceiver; private AutoCloseable mocksCloseable; @Mock private ServiceBusReactorReceiver amqpReceiveLink; @Mock private ServiceBusReactorReceiver sessionReceiveLink; @Mock private ServiceBusAmqpConnection connection; @Mock private TokenCredential tokenCredential; @Mock private MessageSerializer messageSerializer; private ServiceBusReceiverInstrumentation instrumentation = new ServiceBusReceiverInstrumentation(null, null, NAMESPACE, ENTITY_PATH, null, false); @Mock private ServiceBusManagementNode managementNode; @Mock private ServiceBusReceivedMessage receivedMessage; @Mock private ServiceBusReceivedMessage receivedMessage2; @Mock private Runnable onClientClose; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(100)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @BeforeEach void setup(TestInfo testInfo) { LOGGER.info("[{}] Setting up.", testInfo.getDisplayName()); mocksCloseable = MockitoAnnotations.openMocks(this); when(amqpReceiveLink.receive()).thenReturn(messageProcessor.publishOn(Schedulers.single())); when(amqpReceiveLink.getEndpointStates()).thenReturn(endpointProcessor); when(amqpReceiveLink.addCredits(anyInt())).thenReturn(Mono.empty()); when(sessionReceiveLink.receive()).thenReturn(messageProcessor.publishOn(Schedulers.single())); when(sessionReceiveLink.getEndpointStates()).thenReturn(endpointProcessor); when(sessionReceiveLink.addCredits(anyInt())).thenReturn(Mono.empty()); ConnectionOptions connectionOptions = new ConnectionOptions(NAMESPACE, tokenCredential, CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, AmqpTransportType.AMQP, new AmqpRetryOptions(), ProxyOptions.SYSTEM_DEFAULTS, Schedulers.boundedElastic(), CLIENT_OPTIONS, SslDomain.VerifyMode.VERIFY_PEER_NAME, "test-product", "test-version"); when(connection.getEndpointStates()).thenReturn(endpointProcessor); endpointSink.next(AmqpEndpointState.ACTIVE); when(connection.getManagementNode(ENTITY_PATH, ENTITY_TYPE)) .thenReturn(Mono.just(managementNode)); when(connection.createReceiveLink(anyString(), anyString(), any(ServiceBusReceiveMode.class), any(), any(MessagingEntityType.class), anyString())).thenReturn(Mono.just(amqpReceiveLink)); when(connection.createReceiveLink(anyString(), anyString(), any(ServiceBusReceiveMode.class), any(), any(MessagingEntityType.class), anyString(), anyString())).thenReturn(Mono.just(sessionReceiveLink)); connectionProcessor = Flux.<ServiceBusAmqpConnection>create(sink -> sink.next(connection)) .subscribeWith(new ServiceBusConnectionProcessor(connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getRetry())); receiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, false), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); sessionReceiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNamedSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, false, SESSION_ID), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, mock(ServiceBusSessionManager.class)); } @AfterEach void teardown(TestInfo testInfo) throws Exception { LOGGER.info("[{}] Tearing down.", testInfo.getDisplayName()); receiver.close(); mocksCloseable.close(); Mockito.framework().clearInlineMock(this); } /** * Verifies that the correct Service Bus properties are set. */ @Test void properties() { Assertions.assertEquals(ENTITY_PATH, receiver.getEntityPath()); Assertions.assertEquals(NAMESPACE, receiver.getFullyQualifiedNamespace()); Assertions.assertEquals(CLIENT_IDENTIFIER, receiver.getIdentifier()); } /** * Verifies that when user calls peek more than one time, It returns different object. */ @SuppressWarnings("unchecked") @Test void peekTwoMessages() { final long sequence1 = 10; final long sequence2 = 12; final ArgumentCaptor<Long> captor = ArgumentCaptor.forClass(Long.class); when(receivedMessage.getSequenceNumber()).thenReturn(sequence1); when(receivedMessage2.getSequenceNumber()).thenReturn(sequence2); when(managementNode.peek(anyLong(), isNull(), isNull())) .thenReturn(Mono.just(receivedMessage), Mono.just(receivedMessage2)); StepVerifier.create(receiver.peekMessage()) .expectNext(receivedMessage) .verifyComplete(); StepVerifier.create(receiver.peekMessage()) .expectNext(receivedMessage2) .verifyComplete(); verify(managementNode, times(2)).peek(captor.capture(), isNull(), isNull()); final List<Long> allValues = captor.getAllValues(); Assertions.assertEquals(2, allValues.size()); Assertions.assertTrue(allValues.contains(0L)); Assertions.assertTrue(allValues.contains(11L)); } /** * Verifies that when no messages are returned, that it does not error. */ @Test void peekEmptyEntity() { when(managementNode.peek(0, null, null)) .thenReturn(Mono.empty()); StepVerifier.create(receiver.peekMessage()) .verifyComplete(); } /** * Verifies that this peek one messages from a sequence Number. */ @Test void peekWithSequenceOneMessage() { final int fromSequenceNumber = 10; final ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class); when(managementNode.peek(fromSequenceNumber, null, null)).thenReturn(Mono.just(receivedMessage)); StepVerifier.create(receiver.peekMessage(fromSequenceNumber)) .expectNext(receivedMessage) .verifyComplete(); } /** * Verifies that this receives a number of messages. Verifies that the initial credits we add are equal to the * prefetch value. */ @Test void receivesNumberOfEvents() { final int numberOfEvents = 1; final List<Message> messages = getMessages(); final String lockToken = UUID.randomUUID().toString(); ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class); when(receivedMessage.getLockedUntil()).thenReturn(OffsetDateTime.now()); when(receivedMessage.getLockToken()).thenReturn(lockToken); when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class))) .thenReturn(receivedMessage); StepVerifier.create(receiver.receiveMessages().take(numberOfEvents)) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(numberOfEvents) .verifyComplete(); verify(amqpReceiveLink, atMost(numberOfEvents + 1)).addCredits(PREFETCH); verify(amqpReceiveLink, never()).updateDisposition(eq(lockToken), any()); } /** * Verifies that session receiver does not start 'FluxAutoLockRenew' for each message because a session is already * locked. */ @Test void receivesMessageLockRenewSessionOnly() { final int numberOfEvents = 1; final List<Message> messages = getMessages(); final String lockToken = UUID.randomUUID().toString(); final Duration maxLockRenewDuration = Duration.ofMinutes(1); final ServiceBusSessionManager sessionManager = mock(ServiceBusSessionManager.class); ServiceBusReceiverAsyncClient mySessionReceiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNamedSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, maxLockRenewDuration, false, SESSION_ID), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, sessionManager); try ( MockedConstruction<FluxAutoLockRenew> mockedAutoLockRenew = Mockito.mockConstructionWithAnswer(FluxAutoLockRenew.class, invocationOnMock -> new FluxAutoLockRenew(Flux.empty(), createNonSessionOptions(ServiceBusReceiveMode.RECEIVE_AND_DELETE, 1, Duration.ofSeconds(30), true), new LockContainer<>(Duration.ofSeconds(30)), i -> Mono.empty(), NOOP_TRACER))) { ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class); when(receivedMessage.getLockedUntil()).thenReturn(OffsetDateTime.now()); when(receivedMessage.getLockToken()).thenReturn(lockToken); final List<ServiceBusReceivedMessage> sessionMessages = new ArrayList<>(); sessionMessages.add(receivedMessage); when(sessionManager.receive()).thenReturn(Flux.fromIterable(sessionMessages).map(ServiceBusMessageContext::new)); StepVerifier.create(mySessionReceiver.receiveMessages().take(numberOfEvents)) .then(() -> messages.forEach(messageSink::next)) .expectNextCount(numberOfEvents) .verifyComplete(); Assertions.assertEquals(0, mockedAutoLockRenew.constructed().size()); } } public static Stream<DispositionStatus> settleWithNullTransactionId() { return Stream.of(DispositionStatus.DEFERRED, DispositionStatus.ABANDONED, DispositionStatus.COMPLETED, DispositionStatus.SUSPENDED); } /** * Verifies that we error if we try to settle a message with null transaction-id. * * Transactions are not used in {@link ServiceBusReceiverAsyncClient * is package-private, so we skip this case. */ @ParameterizedTest @MethodSource void settleWithNullTransactionId(DispositionStatus dispositionStatus) { ServiceBusTransactionContext nullTransactionId = new ServiceBusTransactionContext(null); when(connection.getManagementNode(ENTITY_PATH, ENTITY_TYPE)).thenReturn(Mono.just(managementNode)); when(managementNode.updateDisposition(any(), eq(dispositionStatus), isNull(), isNull(), isNull(), isNull(), isNull(), isNull())) .thenReturn(Mono.delay(Duration.ofMillis(250)).then()); when(receivedMessage.getLockToken()).thenReturn("mylockToken"); final Mono<Void> operation; switch (dispositionStatus) { case DEFERRED: operation = receiver.defer(receivedMessage, new DeferOptions().setTransactionContext(nullTransactionId)); break; case ABANDONED: operation = receiver.abandon(receivedMessage, new AbandonOptions().setTransactionContext(nullTransactionId)); break; case COMPLETED: operation = receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(nullTransactionId)); break; case SUSPENDED: operation = receiver.deadLetter(receivedMessage, new DeadLetterOptions().setTransactionContext(nullTransactionId)); break; default: throw new IllegalArgumentException("Unrecognized operation: " + dispositionStatus); } StepVerifier.create(operation) .expectError(NullPointerException.class) .verify(); verify(managementNode, never()).updateDisposition(any(), eq(dispositionStatus), isNull(), isNull(), isNull(), isNull(), isNull(), isNull()); } /** * Verifies that we error if we try to complete a null message. */ @Test void completeNullMessage() { StepVerifier.create(receiver.complete(null)).expectError(NullPointerException.class).verify(); } /** * Verifies that we error if we complete in RECEIVE_AND_DELETE mode. */ @Test void completeInReceiveAndDeleteMode() { final ReceiverOptions options = createNonSessionOptions(ServiceBusReceiveMode.RECEIVE_AND_DELETE, PREFETCH, null, false); ServiceBusReceiverAsyncClient client = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, options, connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); final String lockToken1 = UUID.randomUUID().toString(); when(receivedMessage.getLockToken()).thenReturn(lockToken1); try { StepVerifier.create(client.complete(receivedMessage)) .expectError(UnsupportedOperationException.class) .verify(); } finally { client.close(); } } @Test void throwsExceptionAboutSettlingPeekedMessagesWithNullLockToken() { final ReceiverOptions options = createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, false); ServiceBusReceiverAsyncClient client = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, options, connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); when(receivedMessage.getLockToken()).thenReturn(null); try { StepVerifier.create(client.complete(receivedMessage)) .expectError(UnsupportedOperationException.class) .verify(); } finally { client.close(); } } /** * Verifies that this peek batch of messages. */ @Test void peekMessages() { final int numberOfEvents = 2; when(managementNode.peek(0, null, null, numberOfEvents)) .thenReturn(Flux.fromArray(new ServiceBusReceivedMessage[]{receivedMessage, receivedMessage2})); StepVerifier.create(receiver.peekMessages(numberOfEvents)) .expectNextCount(numberOfEvents) .verifyComplete(); } /** * Verifies that this peek batch of messages. */ @Test void peekMessagesEmptyEntity() { final int numberOfEvents = 2; when(managementNode.peek(0, null, null, numberOfEvents)) .thenReturn(Flux.fromIterable(Collections.emptyList())); StepVerifier.create(receiver.peekMessages(numberOfEvents)) .verifyComplete(); } /** * Verifies that this peek batch of messages from a sequence Number. */ @Test void peekBatchWithSequenceNumberMessages() { final int numberOfEvents = 2; final int fromSequenceNumber = 10; when(managementNode.peek(fromSequenceNumber, null, null, numberOfEvents)) .thenReturn(Flux.fromArray(new ServiceBusReceivedMessage[]{receivedMessage, receivedMessage2})); StepVerifier.create(receiver.peekMessages(numberOfEvents, fromSequenceNumber)) .expectNext(receivedMessage, receivedMessage2) .verifyComplete(); } /** * Verifies that we can deadletter a message with an error and description. */ @Test void deadLetterWithDescription() { final String lockToken1 = UUID.randomUUID().toString(); final String description = "some-dead-letter-description"; final String reason = "dead-letter-reason"; final Map<String, Object> propertiesToModify = new HashMap<>(); propertiesToModify.put("something", true); final DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setDeadLetterReason(reason) .setDeadLetterErrorDescription(description) .setPropertiesToModify(propertiesToModify); final OffsetDateTime expiration = OffsetDateTime.now().plus(Duration.ofMinutes(5)); final MessageWithLockToken message = mock(MessageWithLockToken.class); when(messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage); when(receivedMessage.getLockToken()).thenReturn(lockToken1); when(receivedMessage.getLockedUntil()).thenReturn(expiration); when(amqpReceiveLink.updateDisposition(eq(lockToken1), argThat(e -> e.getType() == DeliveryStateType.Rejected))).thenReturn(Mono.empty()); StepVerifier.create(receiver.receiveMessages() .take(1) .flatMap(receivedMessage -> receiver.deadLetter(receivedMessage, deadLetterOptions))) .then(() -> messageSink.next(message)) .expectNext() .verifyComplete(); verify(amqpReceiveLink).updateDisposition(eq(lockToken1), isA(Rejected.class)); } /** * Verifies that error source is populated when any error happened while renewing lock. */ @Test void errorSourceOnRenewMessageLock() { final Duration maxDuration = Duration.ofSeconds(8); final String lockToken = "some-token"; when(receivedMessage.getLockToken()).thenReturn(lockToken); when(receivedMessage.getContext()).thenReturn(Context.NONE); when(managementNode.renewMessageLock(lockToken, null)) .thenReturn(Mono.error(new AzureException("some error occurred."))); final ReceiverOptions receiverOptions = createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, true); final ServiceBusReceiverAsyncClient receiver2 = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, receiverOptions, connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); StepVerifier.create(receiver2.renewMessageLock(receivedMessage, maxDuration)) .verifyErrorSatisfies(throwable -> { Assertions.assertTrue(throwable instanceof ServiceBusException); final ServiceBusErrorSource actual = ((ServiceBusException) throwable).getErrorSource(); Assertions.assertEquals(ServiceBusErrorSource.RENEW_LOCK, actual); }); verify(managementNode, times(1)).renewMessageLock(lockToken, null); } /** * Verifies that error source is populated when any error happened while renewing lock. */ @Test /** * Verifies that error source is populated when there is no autoComplete. */ @ParameterizedTest @MethodSource void errorSourceNoneOnSettlement(DispositionStatus dispositionStatus, DeliveryStateType expectedDeliveryState, ServiceBusErrorSource errorSource) { final UUID lockTokenUuid = UUID.randomUUID(); final String lockToken1 = lockTokenUuid.toString(); final MessageWithLockToken message = mock(MessageWithLockToken.class); when(receivedMessage.getLockToken()).thenReturn(lockToken1); when(messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage); when(amqpReceiveLink.updateDisposition(eq(lockToken1), argThat(e -> e.getType() == expectedDeliveryState))) .thenReturn(Mono.error(new AzureException("some error occurred."))); StepVerifier.create(receiver.receiveMessages().take(1) .flatMap(receivedMessage -> { final Mono<Void> operation; switch (dispositionStatus) { case ABANDONED: operation = receiver.abandon(receivedMessage); break; case COMPLETED: operation = receiver.complete(receivedMessage); break; default: throw new IllegalArgumentException("Unrecognized operation: " + dispositionStatus); } return operation; }) ) .then(() -> messageSink.next(message)) .expectNext() .verifyErrorSatisfies(throwable -> { Assertions.assertTrue(throwable instanceof ServiceBusException); final ServiceBusErrorSource actual = ((ServiceBusException) throwable).getErrorSource(); Assertions.assertEquals(errorSource, actual); }); verify(amqpReceiveLink).updateDisposition(eq(lockToken1), any(DeliveryState.class)); } /** * Ensure that we throw right error source when there is any issue during autocomplete. Error source should be * {@link ServiceBusErrorSource */ @Test void errorSourceAutoCompleteMessage() { final int numberOfEvents = 2; final int messagesToReceive = 1; final List<Message> messages = getMessages(); final String lockToken = UUID.randomUUID().toString(); final ReceiverOptions receiverOptions = createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, true); final ServiceBusReceiverAsyncClient receiver2 = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, receiverOptions, connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); when(receivedMessage.getLockToken()).thenReturn(lockToken); when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class))) .thenReturn(receivedMessage); when(amqpReceiveLink.updateDisposition(lockToken, Accepted.getInstance())).thenReturn(Mono.error(new AmqpException(false, AmqpErrorCondition.MESSAGE_LOCK_LOST, "some error occurred.", null))); try { StepVerifier.create(receiver2.receiveMessages().take(numberOfEvents)) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(messagesToReceive) .verifyErrorSatisfies(throwable -> { Assertions.assertTrue(throwable instanceof ServiceBusException); ServiceBusException serviceBusException = (ServiceBusException) throwable; final ServiceBusErrorSource actual = serviceBusException.getErrorSource(); Assertions.assertEquals(ServiceBusErrorSource.COMPLETE, actual); Assertions.assertEquals(ServiceBusFailureReason.MESSAGE_LOCK_LOST, serviceBusException.getReason()); }); } finally { receiver2.close(); } verify(amqpReceiveLink, atLeast(messagesToReceive)).updateDisposition(lockToken, Accepted.getInstance()); } /** * Verifies that error source is populated when there is any error during receiving of message. */ @Test void errorSourceOnReceiveMessage() { final String lockToken = UUID.randomUUID().toString(); final OffsetDateTime expiration = OffsetDateTime.now().plus(Duration.ofMinutes(5)); final MessageWithLockToken message = mock(MessageWithLockToken.class); when(messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage); when(receivedMessage.getLockToken()).thenReturn(lockToken); when(receivedMessage.getLockedUntil()).thenReturn(expiration); final ReceiverOptions receiverOptions = createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, true); final ServiceBusReceiverAsyncClient receiver2 = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, receiverOptions, connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); when(connection.createReceiveLink(anyString(), anyString(), any(ServiceBusReceiveMode.class), any(), any(MessagingEntityType.class), anyString())).thenReturn(Mono.error(new AzureException("some receive link Error."))); StepVerifier.create(receiver2.receiveMessages().take(1)) .verifyErrorSatisfies(throwable -> { Assertions.assertTrue(throwable instanceof ServiceBusException); final ServiceBusErrorSource actual = ((ServiceBusException) throwable).getErrorSource(); Assertions.assertEquals(ServiceBusErrorSource.RECEIVE, actual); }); verify(amqpReceiveLink, never()).updateDisposition(eq(lockToken), any(DeliveryState.class)); } /** * Verifies that the user can complete settlement methods on received message. */ @ParameterizedTest @EnumSource(DispositionStatus.class) void settleMessageOnManagement(DispositionStatus dispositionStatus) { final String lockToken1 = UUID.randomUUID().toString(); final String lockToken2 = UUID.randomUUID().toString(); final OffsetDateTime expiration = OffsetDateTime.now().plus(Duration.ofMinutes(5)); final long sequenceNumber = 10L; final long sequenceNumber2 = 15L; final MessageWithLockToken message = mock(MessageWithLockToken.class); final MessageWithLockToken message2 = mock(MessageWithLockToken.class); when(messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage); when(messageSerializer.deserialize(message2, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage2); when(receivedMessage.getLockToken()).thenReturn(lockToken1); when(receivedMessage.getLockedUntil()).thenReturn(expiration); when(receivedMessage2.getLockToken()).thenReturn(lockToken2); when(receivedMessage2.getLockedUntil()).thenReturn(expiration); when(connection.getManagementNode(eq(ENTITY_PATH), eq(ENTITY_TYPE))) .thenReturn(Mono.just(managementNode)); when(managementNode.receiveDeferredMessages(eq(ServiceBusReceiveMode.PEEK_LOCK), isNull(), isNull(), argThat(arg -> { boolean foundFirst = false; boolean foundSecond = false; for (Long seq : arg) { if (!foundFirst && sequenceNumber == seq) { foundFirst = true; } else if (!foundSecond && sequenceNumber2 == seq) { foundSecond = true; } } return foundFirst && foundSecond; }))) .thenReturn(Flux.just(receivedMessage, receivedMessage2)); when(managementNode.updateDisposition(lockToken1, dispositionStatus, null, null, null, null, null, null)) .thenReturn(Mono.empty()); when(managementNode.updateDisposition(lockToken2, dispositionStatus, null, null, null, null, null, null)) .thenReturn(Mono.empty()); StepVerifier.create(receiver.receiveDeferredMessages(Arrays.asList(sequenceNumber, sequenceNumber2))) .expectNext(receivedMessage, receivedMessage2) .verifyComplete(); final Mono<Void> operation; switch (dispositionStatus) { case DEFERRED: operation = receiver.defer(receivedMessage); break; case ABANDONED: operation = receiver.abandon(receivedMessage); break; case COMPLETED: operation = receiver.complete(receivedMessage); break; case SUSPENDED: operation = receiver.deadLetter(receivedMessage); break; case RELEASED: operation = receiver.release(receivedMessage); break; default: throw new IllegalArgumentException("Unrecognized operation: " + dispositionStatus); } StepVerifier.create(operation) .verifyComplete(); verify(managementNode).updateDisposition(lockToken1, dispositionStatus, null, null, null, null, null, null); verify(managementNode, never()).updateDisposition(lockToken2, dispositionStatus, null, null, null, null, null, null); } /** * Verifies that this receive deferred one messages from a sequence Number. */ @Test void receiveDeferredWithSequenceOneMessage() { final int fromSequenceNumber = 10; final ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class); when(managementNode.receiveDeferredMessages(any(), any(), any(), any())).thenReturn(Flux.just(receivedMessage)); StepVerifier.create(receiver.receiveDeferredMessage(fromSequenceNumber)) .expectNext(receivedMessage) .verifyComplete(); } /** * Verifies that this receive deferred messages from a sequence Number. */ @Test void receiveDeferredBatchFromSequenceNumber() { final long fromSequenceNumber1 = 10; final long fromSequenceNumber2 = 11; when(managementNode.receiveDeferredMessages(any(), any(), any(), any())) .thenReturn(Flux.fromArray(new ServiceBusReceivedMessage[]{receivedMessage, receivedMessage2})); StepVerifier.create(receiver.receiveDeferredMessages(Arrays.asList(fromSequenceNumber1, fromSequenceNumber2))) .expectNext(receivedMessage) .expectNext(receivedMessage2) .verifyComplete(); } /** * Verifies that the onClientClose is called. */ @Test void callsClientClose() { receiver.close(); verify(onClientClose).run(); } /** * Verifies that the onClientClose is only called once. */ @Test void callsClientCloseOnce() { receiver.close(); receiver.close(); verify(onClientClose).run(); } /** * Verifies that managementNodeLocks was closed. */ @Test void callsManagementNodeLocksCloseWhenClientIsClosed() { Assertions.assertFalse(receiver.isManagementNodeLocksClosed()); receiver.close(); Assertions.assertTrue(receiver.isManagementNodeLocksClosed()); } /** * Verifies that renewalContainer was closed. */ @Test void callsRenewalContainerCloseWhenClientIsClosed() { Assertions.assertFalse(receiver.isRenewalContainerClosed()); receiver.close(); Assertions.assertTrue(receiver.isRenewalContainerClosed()); } /** * Tests that invalid options throws and null options. */ @Test void receiveIllegalOptions() { ServiceBusReceiverClientBuilder builder = new ServiceBusClientBuilder() .connectionString(NAMESPACE_CONNECTION_STRING) .receiver() .topicName("baz").subscriptionName("bar") .receiveMode(ServiceBusReceiveMode.PEEK_LOCK); Assertions.assertThrows(IllegalArgumentException.class, () -> builder.prefetchCount(-1)); } @Test void topicCorrectEntityPath() { final String topicName = "foo"; final String subscriptionName = "bar"; final String entityPath = String.join("/", topicName, "subscriptions", subscriptionName); final ServiceBusReceiverAsyncClient receiver = new ServiceBusClientBuilder() .connectionString(NAMESPACE_CONNECTION_STRING) .receiver() .topicName(topicName) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .buildAsyncClient(); final String actual = receiver.getEntityPath(); final String actualNamespace = receiver.getFullyQualifiedNamespace(); Assertions.assertEquals(entityPath, actual); Assertions.assertEquals(NAMESPACE, actualNamespace); } /** * Verifies that client can call multiple receiveMessages on same receiver instance. */ @Test void canPerformMultipleReceive() { final int numberOfEvents = 1; final List<Message> messages = getMessages(); ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class); when(receivedMessage.getLockedUntil()).thenReturn(OffsetDateTime.now()); when(receivedMessage.getLockToken()).thenReturn(UUID.randomUUID().toString()); when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class))) .thenReturn(receivedMessage); StepVerifier.create(receiver.receiveMessages().take(numberOfEvents)) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(numberOfEvents) .verifyComplete(); verify(amqpReceiveLink, atMost(numberOfEvents + 1)).addCredits(PREFETCH); } /** * Cannot get session state for non-session receiver. */ @Test void cannotPerformGetSessionState() { StepVerifier.create(receiver.getSessionState()) .expectError(IllegalStateException.class) .verify(); } /** * Cannot get session state for non-session receiver. */ @Test void cannotPerformSetSessionState() { final String sessionId = "a-session-id"; final byte[] sessionState = new byte[]{10, 11, 8}; StepVerifier.create(receiver.setSessionState(sessionState)) .expectError(IllegalStateException.class) .verify(); } /** * Cannot get session state for non-session receiver. */ @Test void cannotPerformRenewSessionLock() { StepVerifier.create(receiver.renewSessionLock()) .expectError(IllegalStateException.class) .verify(); } /** * Verifies that we can get a session state. */ @SuppressWarnings("unchecked") @Test void getSessionState() { final byte[] bytes = new byte[]{95, 11, 54, 10}; ServiceBusReceiverAsyncClient mySessionReceiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNamedSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, CLEANUP_INTERVAL, false, SESSION_ID), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, mock(ServiceBusSessionManager.class)); when(managementNode.getSessionState(SESSION_ID, null)) .thenReturn(Mono.just(bytes)); StepVerifier.create(mySessionReceiver.getSessionState()) .expectNext(bytes) .expectComplete() .verify(); } /** * Verifies that we can set a session state. */ @Test void setSessionState() { final byte[] bytes = new byte[]{95, 11, 54, 10}; when(managementNode.setSessionState(SESSION_ID, bytes, null)).thenReturn(Mono.empty()); StepVerifier.create(sessionReceiver.setSessionState(bytes)) .expectComplete() .verify(); } /** * Get null session id for non-session receiver and gets valid session id for a session receiver. */ @Test void getSessionIdTests() { Assertions.assertNull(receiver.getSessionId(), "Non-null session Id for a non-session receiver"); Assertions.assertEquals(SESSION_ID, sessionReceiver.getSessionId()); } /** * Verifies that we can renew a session state. */ @Test void renewSessionLock() { final OffsetDateTime expiry = Instant.ofEpochSecond(1588011761L).atOffset(ZoneOffset.UTC); when(managementNode.renewSessionLock(SESSION_ID, null)).thenReturn(Mono.just(expiry)); StepVerifier.create(sessionReceiver.renewSessionLock()) .expectNext(expiry) .expectComplete() .verify(); } /** * Verifies that we cannot renew a message lock when using a session receiver. */ @Test void cannotRenewMessageLockInSession() { when(receivedMessage.getLockToken()).thenReturn("lock-token"); when(receivedMessage.getSessionId()).thenReturn("fo"); StepVerifier.create(sessionReceiver.renewMessageLock(receivedMessage)) .expectError(IllegalStateException.class) .verify(); } /** * Verifies that we can auto-renew a message lock. */ @Test void autoRenewMessageLock() { final Duration maxDuration = Duration.ofSeconds(8); final Duration renewalPeriod = Duration.ofSeconds(3); final UUID lockTokenUUID = UUID.randomUUID(); final String lockToken = lockTokenUUID.toString(); final ServiceBusReceivedMessage message = new ServiceBusReceivedMessage(BinaryData.fromString("foo")); message.setLockToken(lockTokenUUID); final int atMost = 6; final Duration totalSleepPeriod = maxDuration.plusMillis(500); when(managementNode.renewMessageLock(lockToken, null)) .thenReturn(Mono.fromCallable(() -> OffsetDateTime.now().plus(renewalPeriod))); StepVerifier.create(receiver.renewMessageLock(message, maxDuration)) .thenAwait(totalSleepPeriod) .then(() -> LOGGER.info("Finished renewals for first sleep.")) .expectComplete() .verify(Duration.ofSeconds(5)); verify(managementNode, Mockito.atMost(atMost)).renewMessageLock(lockToken, null); } /** * Verifies that it errors when we try a null lock token. */ @Test void autoRenewMessageLockErrorNull() { final Duration maxDuration = Duration.ofSeconds(8); final Duration renewalPeriod = Duration.ofSeconds(3); when(receivedMessage.getLockToken()).thenReturn(null); when(managementNode.renewMessageLock(anyString(), isNull())) .thenReturn(Mono.fromCallable(() -> OffsetDateTime.now().plus(renewalPeriod))); StepVerifier.create(receiver.renewMessageLock(receivedMessage, maxDuration)) .expectError(NullPointerException.class) .verify(); verify(managementNode, never()).renewMessageLock(anyString(), isNull()); } /** * Verifies that it errors when we try an empty string lock token. */ @Test void autoRenewMessageLockErrorEmptyString() { final Duration maxDuration = Duration.ofSeconds(8); final Duration renewalPeriod = Duration.ofSeconds(3); final String lockToken = ""; when(receivedMessage.getLockToken()).thenReturn(""); when(managementNode.renewMessageLock(anyString(), isNull())) .thenReturn(Mono.fromCallable(() -> OffsetDateTime.now().plus(renewalPeriod))); StepVerifier.create(receiver.renewMessageLock(receivedMessage, maxDuration)) .expectError(IllegalArgumentException.class) .verify(); verify(managementNode, never()).renewMessageLock(anyString(), isNull()); } /** * Verifies that we can auto-renew a session lock. */ @Test void autoRenewSessionLock() { final Duration maxDuration = Duration.ofSeconds(8); final Duration renewalPeriod = Duration.ofSeconds(3); final String sessionId = "some-token"; final int atMost = 6; final Duration totalSleepPeriod = maxDuration.plusMillis(500); when(managementNode.renewSessionLock(SESSION_ID, null)) .thenReturn(Mono.fromCallable(() -> OffsetDateTime.now().plus(renewalPeriod))); StepVerifier.create(sessionReceiver.renewSessionLock(maxDuration)) .thenAwait(totalSleepPeriod) .then(() -> LOGGER.info("Finished renewals for first sleep.")) .expectComplete() .verify(Duration.ofSeconds(5)); verify(managementNode, Mockito.atMost(atMost)).renewSessionLock(sessionId, null); } /** * Verifies that it errors if session renewal is tried on session unaware receiver. */ @Test void cannotRenewSessionLockForNonSessionReceiver() { StepVerifier.create(receiver.renewSessionLock()) .expectError(IllegalStateException.class) .verify(); } @Test void autoCompleteMessage() { final int numberOfEvents = 3; final List<Message> messages = getMessages(); final String lockToken = UUID.randomUUID().toString(); final ReceiverOptions receiverOptions = createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, true); final ServiceBusReceiverAsyncClient receiver2 = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, receiverOptions, connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); when(receivedMessage.getLockToken()).thenReturn(lockToken); when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class))) .thenReturn(receivedMessage); when(amqpReceiveLink.updateDisposition(lockToken, Accepted.getInstance())).thenReturn(Mono.empty()); try { StepVerifier.create(receiver2.receiveMessages().take(numberOfEvents)) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(numberOfEvents) .verifyComplete(); } finally { receiver2.close(); } verify(amqpReceiveLink, times(numberOfEvents)).updateDisposition(lockToken, Accepted.getInstance()); } @Test void autoCompleteMessageSessionReceiver() { final int numberOfEvents = 3; final List<Message> messages = getMessages(); final String lockToken = "token1"; final String lockToken2 = "token2"; final String lockToken3 = "token3"; final ServiceBusSessionManager sessionManager = mock(ServiceBusSessionManager.class); final ReceiverOptions receiverOptions = createNamedSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, true, SESSION_ID); final ServiceBusReceiverAsyncClient sessionReceiver2 = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, receiverOptions, connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, sessionManager); final ServiceBusReceivedMessage receivedMessage3 = mock(ServiceBusReceivedMessage.class); when(receivedMessage.getLockToken()).thenReturn(lockToken); when(receivedMessage2.getLockToken()).thenReturn(lockToken2); when(receivedMessage3.getLockToken()).thenReturn(lockToken3); final List<ServiceBusReceivedMessage> sessionMessages = new ArrayList<>(); sessionMessages.add(receivedMessage); sessionMessages.add(receivedMessage2); sessionMessages.add(receivedMessage3); when(sessionManager.receive()).thenReturn(Flux.fromIterable(sessionMessages).map(ServiceBusMessageContext::new)); when(sessionManager.updateDisposition(eq(lockToken), any(), eq(DispositionStatus.COMPLETED), any(), any(), any(), any())).thenReturn(Mono.empty()); when(sessionManager.updateDisposition(eq(lockToken2), any(), eq(DispositionStatus.COMPLETED), any(), any(), any(), any())).thenReturn(Mono.empty()); when(sessionManager.updateDisposition(eq(lockToken3), any(), eq(DispositionStatus.COMPLETED), any(), any(), any(), any())).thenReturn(Mono.empty()); try { StepVerifier.create(sessionReceiver2.receiveMessages().take(numberOfEvents)) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(numberOfEvents) .verifyComplete(); } finally { sessionReceiver2.close(); } verify(sessionManager).updateDisposition(eq(lockToken), any(), any(), any(), any(), any(), any()); verify(sessionManager).updateDisposition(eq(lockToken2), any(), any(), any(), any(), any(), any()); verify(sessionManager).updateDisposition(eq(lockToken3), any(), any(), any(), any(), any(), any()); } @Test void receiveMessagesReportsMetricsAsyncInstr() { final List<Message> messages = getMessages(); TestMeter meter = new TestMeter(); ServiceBusReceiverInstrumentation instrumentation = new ServiceBusReceiverInstrumentation(null, meter, NAMESPACE, ENTITY_PATH, SUBSCRIPTION_NAME, false); receiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, false), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); ServiceBusReceivedMessage receivedMessage1 = mockReceivedMessage(Instant.now().minusSeconds(1000)); ServiceBusReceivedMessage receivedMessage2 = mockReceivedMessage(Instant.now().minusSeconds(500)); when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class))) .thenReturn(receivedMessage1, receivedMessage2); StepVerifier.create(receiver.receiveMessages().take(2)) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(2) .verifyComplete(); TestHistogram receiverLag = meter.getHistograms().get("messaging.servicebus.receiver.lag"); assertNotNull(receiverLag); assertEquals(2, receiverLag.getMeasurements().size()); TestMeasurement<Double> measurement1 = receiverLag.getMeasurements().get(0); TestMeasurement<Double> measurement2 = receiverLag.getMeasurements().get(1); assertEquals(1000d, measurement1.getValue(), 10d); assertEquals(500d, measurement2.getValue(), 10d); Map<String, Object> attributes1 = measurement1.getAttributes(); Map<String, Object> attributes2 = measurement2.getAttributes(); assertEquals(3, attributes1.size()); assertCommonMetricAttributes(attributes1, SUBSCRIPTION_NAME); assertEquals(3, attributes2.size()); assertCommonMetricAttributes(attributes2, SUBSCRIPTION_NAME); } @ParameterizedTest() @EnumSource(DispositionStatus.class) void settlementMessagesReportsMetrics(DispositionStatus status) { final List<Message> messages = getMessages(); TestMeter meter = new TestMeter(); ServiceBusReceiverInstrumentation instrumentation = new ServiceBusReceiverInstrumentation(null, meter, NAMESPACE, ENTITY_PATH, SUBSCRIPTION_NAME, false); receiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, false), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); when(receivedMessage.getLockToken()).thenReturn("mylockToken"); when(receivedMessage.getSequenceNumber()).thenReturn(42L); when(receivedMessage.getContext()).thenReturn(Context.NONE); when(managementNode.updateDisposition(any(), any(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull())).thenReturn(Mono.empty()); Mono<Void> settle; switch (status) { case COMPLETED: { settle = receiver.complete(receivedMessage); break; } case ABANDONED: { settle = receiver.abandon(receivedMessage); break; } case DEFERRED: { settle = receiver.defer(receivedMessage); break; } case SUSPENDED: { settle = receiver.deadLetter(receivedMessage); break; } default: { return; } } StepVerifier.create(settle).verifyComplete(); TestHistogram settlementDuration = meter.getHistograms().get("messaging.servicebus.settlement.request.duration"); assertNotNull(settlementDuration); assertEquals(1, settlementDuration.getMeasurements().size()); TestMeasurement<Double> measurement = settlementDuration.getMeasurements().get(0); assertEquals(5000d, measurement.getValue(), 5000d); Map<String, Object> attributes = measurement.getAttributes(); assertEquals(5, attributes.size()); assertCommonMetricAttributes(attributes, SUBSCRIPTION_NAME); assertEquals(status.getValue(), attributes.get("dispositionStatus")); assertEquals("ok", attributes.get("status")); TestGauge settlementSeqNo = meter.getGauges().get("messaging.servicebus.settlement.sequence_number"); assertEquals(10, settlementSeqNo.getSubscriptions().size()); settlementSeqNo.getSubscriptions().forEach(s -> s.measure()); boolean measurementFound = false; for (TestGauge.Subscription subs : settlementSeqNo.getSubscriptions()) { assertEquals(1, subs.getMeasurements().size()); TestMeasurement<Long> seqNoMeasurement = subs.getMeasurements().get(0); if (seqNoMeasurement.getAttributes().get("dispositionStatus").equals(status.getValue()) && seqNoMeasurement.getAttributes().get("status").equals("ok")) { measurementFound = true; assertEquals(42, seqNoMeasurement.getValue()); assertEquals(5, seqNoMeasurement.getAttributes().size()); assertCommonMetricAttributes(seqNoMeasurement.getAttributes(), SUBSCRIPTION_NAME); } else { assertEquals(0, seqNoMeasurement.getValue()); assertEquals(5, seqNoMeasurement.getAttributes().size()); assertCommonMetricAttributes(seqNoMeasurement.getAttributes(), SUBSCRIPTION_NAME); } } assertTrue(measurementFound); } @Test void receiveWithTracesAndMetrics() { final List<Message> messages = getMessages(); TestMeter meter = new TestMeter(); Tracer tracer = mock(Tracer.class); when(tracer.isEnabled()).thenReturn(true); ServiceBusReceiverInstrumentation instrumentation = new ServiceBusReceiverInstrumentation(tracer, meter, NAMESPACE, ENTITY_PATH, SUBSCRIPTION_NAME, false); receiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, false), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); Context spanReceive1 = new Context("marker1", true); Context spanReceive2 = new Context("marker2", true); Context spanSettle = new Context("marker3", true); when(tracer.start(eq("ServiceBus.process"), any(StartSpanOptions.class), any(Context.class))).thenReturn(spanReceive1, spanReceive2); when(tracer.start(eq("ServiceBus.complete"), any(StartSpanOptions.class), any(Context.class))).thenReturn(spanSettle); when(receivedMessage.getLockToken()).thenReturn("mylockToken"); when(receivedMessage.getSequenceNumber()).thenReturn(42L); when(receivedMessage.getContext()).thenReturn(Context.NONE); when(receivedMessage2.getLockToken()).thenReturn("mylockToken"); when(receivedMessage2.getSequenceNumber()).thenReturn(43L); when(receivedMessage2.getContext()).thenReturn(Context.NONE); when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class))) .thenReturn(receivedMessage, receivedMessage2); when(managementNode.updateDisposition(any(), any(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull())).thenReturn(Mono.empty()); when(amqpReceiveLink.updateDisposition(any(), any())).thenReturn(Mono.empty()); StepVerifier.create(receiver.receiveMessages().take(2).flatMap(msg -> receiver.complete(msg))) .then(() -> messages.forEach(m -> messageSink.next(m))) .verifyComplete(); TestHistogram receiverLag = meter.getHistograms().get("messaging.servicebus.receiver.lag"); assertEquals(2, receiverLag.getMeasurements().size()); TestMeasurement<Double> measurement1 = receiverLag.getMeasurements().get(0); TestMeasurement<Double> measurement2 = receiverLag.getMeasurements().get(1); assertEquals(spanReceive1, measurement1.getContext()); assertEquals(spanReceive2, measurement2.getContext()); TestHistogram settlementDuration = meter.getHistograms().get("messaging.servicebus.settlement.request.duration"); assertEquals(spanSettle, settlementDuration.getMeasurements().get(0).getContext()); TestGauge settlementSeqNo = meter.getGauges().get("messaging.servicebus.settlement.sequence_number"); TestGauge.Subscription subs = settlementSeqNo.getSubscriptions().get(0); subs.measure(); assertSame(Context.NONE, subs.getMeasurements().get(0).getContext()); } @Test void receiveMessageNegativeLagReportsMetricsAsyncInstr() { final List<Message> messages = getMessages(); TestMeter meter = new TestMeter(); ServiceBusReceiverInstrumentation instrumentation = new ServiceBusReceiverInstrumentation(null, meter, NAMESPACE, ENTITY_PATH, null, false); receiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, false), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); ServiceBusReceivedMessage receivedMessage1 = mockReceivedMessage(Instant.now().plusSeconds(1000)); when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class))) .thenReturn(receivedMessage1); StepVerifier.create(receiver.receiveMessages().take(1)) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(1) .verifyComplete(); TestHistogram receiverLag = meter.getHistograms().get("messaging.servicebus.receiver.lag"); assertEquals(1, receiverLag.getMeasurements().size()); TestMeasurement<Double> measurement = receiverLag.getMeasurements().get(0); assertEquals(0d, measurement.getValue(), 1d); Map<String, Object> attributes = measurement.getAttributes(); assertEquals(2, attributes.size()); assertCommonMetricAttributes(attributes, null); } @Test void receiveMessageNegativeLagReportsMetricsSyncInstr() { final List<Message> messages = getMessages(); TestMeter meter = new TestMeter(); ServiceBusReceiverInstrumentation instrumentation = new ServiceBusReceiverInstrumentation(null, meter, NAMESPACE, ENTITY_PATH, null, true); receiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, false), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); ServiceBusReceivedMessage receivedMessage1 = mockReceivedMessage(Instant.now()); when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class))) .thenReturn(receivedMessage1); StepVerifier.create(receiver.receiveMessages().take(1)) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(1) .verifyComplete(); TestHistogram receiverLag = meter.getHistograms().get("messaging.servicebus.receiver.lag"); assertEquals(1, receiverLag.getMeasurements().size()); TestMeasurement<Double> measurement = receiverLag.getMeasurements().get(0); Map<String, Object> attributes = measurement.getAttributes(); assertEquals(2, attributes.size()); assertCommonMetricAttributes(attributes, null); } private ServiceBusReceivedMessage mockReceivedMessage(Instant enqueuedTime) { ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class); when(receivedMessage.getLockedUntil()).thenReturn(OffsetDateTime.now()); when(receivedMessage.getLockToken()).thenReturn(UUID.randomUUID().toString()); when(receivedMessage.getEnqueuedTime()).thenReturn(enqueuedTime.atOffset(ZoneOffset.UTC)); return receivedMessage; } private List<Message> getMessages() { final Map<String, String> map = Collections.singletonMap("SAMPLE_HEADER", "foo"); return IntStream.range(0, 10) .mapToObj(index -> getMessage(PAYLOAD_BYTES, messageTrackingUUID, map)) .collect(Collectors.toList()); } private static Stream<Arguments> errorSourceNoneOnSettlement() { return Stream.of( Arguments.of(DispositionStatus.COMPLETED, DeliveryStateType.Accepted, ServiceBusErrorSource.COMPLETE), Arguments.of(DispositionStatus.ABANDONED, DeliveryStateType.Modified, ServiceBusErrorSource.ABANDON)); } private void assertCommonMetricAttributes(Map<String, Object> attributes, String subscriptionName) { assertEquals(NAMESPACE, attributes.get("hostName")); assertEquals(ENTITY_PATH, attributes.get("entityName")); assertEquals(subscriptionName, attributes.get("subscriptionName")); } }
class ServiceBusReceiverAsyncClientTest { private static final ClientOptions CLIENT_OPTIONS = new ClientOptions(); private static final String PAYLOAD = "hello"; private static final byte[] PAYLOAD_BYTES = PAYLOAD.getBytes(UTF_8); private static final int PREFETCH = 5; private static final String NAMESPACE = "my-namespace-foo.net"; private static final String ENTITY_PATH = "queue-name"; private static final String SUBSCRIPTION_NAME = "subscription-name"; private static final MessagingEntityType ENTITY_TYPE = MessagingEntityType.QUEUE; private static final String NAMESPACE_CONNECTION_STRING = String.format( "Endpoint=sb: NAMESPACE, "some-name", "something-else"); private static final Duration CLEANUP_INTERVAL = Duration.ofSeconds(10); private static final String SESSION_ID = "my-session-id"; private static final String CLIENT_IDENTIFIER = "my-client-identifier"; private static final ClientLogger LOGGER = new ClientLogger(ServiceBusReceiverAsyncClientTest.class); private static final ServiceBusTracer NOOP_TRACER = new ServiceBusTracer(null, NAMESPACE, ENTITY_PATH); private final String messageTrackingUUID = UUID.randomUUID().toString(); private final ReplayProcessor<AmqpEndpointState> endpointProcessor = ReplayProcessor.cacheLast(); private final FluxSink<AmqpEndpointState> endpointSink = endpointProcessor.sink(FluxSink.OverflowStrategy.BUFFER); private final DirectProcessor<Message> messageProcessor = DirectProcessor.create(); private final FluxSink<Message> messageSink = messageProcessor.sink(FluxSink.OverflowStrategy.BUFFER); private ServiceBusConnectionProcessor connectionProcessor; private ServiceBusReceiverAsyncClient receiver; private ServiceBusReceiverAsyncClient sessionReceiver; private AutoCloseable mocksCloseable; @Mock private ServiceBusReactorReceiver amqpReceiveLink; @Mock private ServiceBusReactorReceiver sessionReceiveLink; @Mock private ServiceBusAmqpConnection connection; @Mock private TokenCredential tokenCredential; @Mock private MessageSerializer messageSerializer; private ServiceBusReceiverInstrumentation instrumentation = new ServiceBusReceiverInstrumentation(null, null, NAMESPACE, ENTITY_PATH, null, false); @Mock private ServiceBusManagementNode managementNode; @Mock private ServiceBusReceivedMessage receivedMessage; @Mock private ServiceBusReceivedMessage receivedMessage2; @Mock private Runnable onClientClose; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(100)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @BeforeEach void setup(TestInfo testInfo) { LOGGER.info("[{}] Setting up.", testInfo.getDisplayName()); mocksCloseable = MockitoAnnotations.openMocks(this); when(amqpReceiveLink.receive()).thenReturn(messageProcessor.publishOn(Schedulers.single())); when(amqpReceiveLink.getEndpointStates()).thenReturn(endpointProcessor); when(amqpReceiveLink.addCredits(anyInt())).thenReturn(Mono.empty()); when(sessionReceiveLink.receive()).thenReturn(messageProcessor.publishOn(Schedulers.single())); when(sessionReceiveLink.getEndpointStates()).thenReturn(endpointProcessor); when(sessionReceiveLink.addCredits(anyInt())).thenReturn(Mono.empty()); ConnectionOptions connectionOptions = new ConnectionOptions(NAMESPACE, tokenCredential, CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, AmqpTransportType.AMQP, new AmqpRetryOptions(), ProxyOptions.SYSTEM_DEFAULTS, Schedulers.boundedElastic(), CLIENT_OPTIONS, SslDomain.VerifyMode.VERIFY_PEER_NAME, "test-product", "test-version"); when(connection.getEndpointStates()).thenReturn(endpointProcessor); endpointSink.next(AmqpEndpointState.ACTIVE); when(connection.getManagementNode(ENTITY_PATH, ENTITY_TYPE)) .thenReturn(Mono.just(managementNode)); when(connection.createReceiveLink(anyString(), anyString(), any(ServiceBusReceiveMode.class), any(), any(MessagingEntityType.class), anyString())).thenReturn(Mono.just(amqpReceiveLink)); when(connection.createReceiveLink(anyString(), anyString(), any(ServiceBusReceiveMode.class), any(), any(MessagingEntityType.class), anyString(), anyString())).thenReturn(Mono.just(sessionReceiveLink)); connectionProcessor = Flux.<ServiceBusAmqpConnection>create(sink -> sink.next(connection)) .subscribeWith(new ServiceBusConnectionProcessor(connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getRetry())); receiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, false), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); sessionReceiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNamedSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, false, SESSION_ID), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, mock(ServiceBusSessionManager.class)); } @AfterEach void teardown(TestInfo testInfo) throws Exception { LOGGER.info("[{}] Tearing down.", testInfo.getDisplayName()); receiver.close(); mocksCloseable.close(); Mockito.framework().clearInlineMock(this); } /** * Verifies that the correct Service Bus properties are set. */ @Test void properties() { Assertions.assertEquals(ENTITY_PATH, receiver.getEntityPath()); Assertions.assertEquals(NAMESPACE, receiver.getFullyQualifiedNamespace()); Assertions.assertEquals(CLIENT_IDENTIFIER, receiver.getIdentifier()); } /** * Verifies that when user calls peek more than one time, It returns different object. */ @SuppressWarnings("unchecked") @Test void peekTwoMessages() { final long sequence1 = 10; final long sequence2 = 12; final ArgumentCaptor<Long> captor = ArgumentCaptor.forClass(Long.class); when(receivedMessage.getSequenceNumber()).thenReturn(sequence1); when(receivedMessage2.getSequenceNumber()).thenReturn(sequence2); when(managementNode.peek(anyLong(), isNull(), isNull())) .thenReturn(Mono.just(receivedMessage), Mono.just(receivedMessage2)); StepVerifier.create(receiver.peekMessage()) .expectNext(receivedMessage) .verifyComplete(); StepVerifier.create(receiver.peekMessage()) .expectNext(receivedMessage2) .verifyComplete(); verify(managementNode, times(2)).peek(captor.capture(), isNull(), isNull()); final List<Long> allValues = captor.getAllValues(); Assertions.assertEquals(2, allValues.size()); Assertions.assertTrue(allValues.contains(0L)); Assertions.assertTrue(allValues.contains(11L)); } /** * Verifies that when no messages are returned, that it does not error. */ @Test void peekEmptyEntity() { when(managementNode.peek(0, null, null)) .thenReturn(Mono.empty()); StepVerifier.create(receiver.peekMessage()) .verifyComplete(); } /** * Verifies that this peek one messages from a sequence Number. */ @Test void peekWithSequenceOneMessage() { final int fromSequenceNumber = 10; final ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class); when(managementNode.peek(fromSequenceNumber, null, null)).thenReturn(Mono.just(receivedMessage)); StepVerifier.create(receiver.peekMessage(fromSequenceNumber)) .expectNext(receivedMessage) .verifyComplete(); } /** * Verifies that this receives a number of messages. Verifies that the initial credits we add are equal to the * prefetch value. */ @Test void receivesNumberOfEvents() { final int numberOfEvents = 1; final List<Message> messages = getMessages(); final String lockToken = UUID.randomUUID().toString(); ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class); when(receivedMessage.getLockedUntil()).thenReturn(OffsetDateTime.now()); when(receivedMessage.getLockToken()).thenReturn(lockToken); when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class))) .thenReturn(receivedMessage); StepVerifier.create(receiver.receiveMessages().take(numberOfEvents)) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(numberOfEvents) .verifyComplete(); verify(amqpReceiveLink, atMost(numberOfEvents + 1)).addCredits(PREFETCH); verify(amqpReceiveLink, never()).updateDisposition(eq(lockToken), any()); } /** * Verifies that session receiver does not start 'FluxAutoLockRenew' for each message because a session is already * locked. */ @Test void receivesMessageLockRenewSessionOnly() { final int numberOfEvents = 1; final List<Message> messages = getMessages(); final String lockToken = UUID.randomUUID().toString(); final Duration maxLockRenewDuration = Duration.ofMinutes(1); final ServiceBusSessionManager sessionManager = mock(ServiceBusSessionManager.class); ServiceBusReceiverAsyncClient mySessionReceiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNamedSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, maxLockRenewDuration, false, SESSION_ID), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, sessionManager); try ( MockedConstruction<FluxAutoLockRenew> mockedAutoLockRenew = Mockito.mockConstructionWithAnswer(FluxAutoLockRenew.class, invocationOnMock -> new FluxAutoLockRenew(Flux.empty(), createNonSessionOptions(ServiceBusReceiveMode.RECEIVE_AND_DELETE, 1, Duration.ofSeconds(30), true), new LockContainer<>(Duration.ofSeconds(30)), i -> Mono.empty(), NOOP_TRACER))) { ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class); when(receivedMessage.getLockedUntil()).thenReturn(OffsetDateTime.now()); when(receivedMessage.getLockToken()).thenReturn(lockToken); final List<ServiceBusReceivedMessage> sessionMessages = new ArrayList<>(); sessionMessages.add(receivedMessage); when(sessionManager.receive()).thenReturn(Flux.fromIterable(sessionMessages).map(ServiceBusMessageContext::new)); StepVerifier.create(mySessionReceiver.receiveMessages().take(numberOfEvents)) .then(() -> messages.forEach(messageSink::next)) .expectNextCount(numberOfEvents) .verifyComplete(); Assertions.assertEquals(0, mockedAutoLockRenew.constructed().size()); } } public static Stream<DispositionStatus> settleWithNullTransactionId() { return Stream.of(DispositionStatus.DEFERRED, DispositionStatus.ABANDONED, DispositionStatus.COMPLETED, DispositionStatus.SUSPENDED); } /** * Verifies that we error if we try to settle a message with null transaction-id. * * Transactions are not used in {@link ServiceBusReceiverAsyncClient * is package-private, so we skip this case. */ @ParameterizedTest @MethodSource void settleWithNullTransactionId(DispositionStatus dispositionStatus) { ServiceBusTransactionContext nullTransactionId = new ServiceBusTransactionContext(null); when(connection.getManagementNode(ENTITY_PATH, ENTITY_TYPE)).thenReturn(Mono.just(managementNode)); when(managementNode.updateDisposition(any(), eq(dispositionStatus), isNull(), isNull(), isNull(), isNull(), isNull(), isNull())) .thenReturn(Mono.delay(Duration.ofMillis(250)).then()); when(receivedMessage.getLockToken()).thenReturn("mylockToken"); final Mono<Void> operation; switch (dispositionStatus) { case DEFERRED: operation = receiver.defer(receivedMessage, new DeferOptions().setTransactionContext(nullTransactionId)); break; case ABANDONED: operation = receiver.abandon(receivedMessage, new AbandonOptions().setTransactionContext(nullTransactionId)); break; case COMPLETED: operation = receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(nullTransactionId)); break; case SUSPENDED: operation = receiver.deadLetter(receivedMessage, new DeadLetterOptions().setTransactionContext(nullTransactionId)); break; default: throw new IllegalArgumentException("Unrecognized operation: " + dispositionStatus); } StepVerifier.create(operation) .expectError(NullPointerException.class) .verify(); verify(managementNode, never()).updateDisposition(any(), eq(dispositionStatus), isNull(), isNull(), isNull(), isNull(), isNull(), isNull()); } /** * Verifies that we error if we try to complete a null message. */ @Test void completeNullMessage() { StepVerifier.create(receiver.complete(null)).expectError(NullPointerException.class).verify(); } /** * Verifies that we error if we complete in RECEIVE_AND_DELETE mode. */ @Test void completeInReceiveAndDeleteMode() { final ReceiverOptions options = createNonSessionOptions(ServiceBusReceiveMode.RECEIVE_AND_DELETE, PREFETCH, null, false); ServiceBusReceiverAsyncClient client = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, options, connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); final String lockToken1 = UUID.randomUUID().toString(); when(receivedMessage.getLockToken()).thenReturn(lockToken1); try { StepVerifier.create(client.complete(receivedMessage)) .expectError(UnsupportedOperationException.class) .verify(); } finally { client.close(); } } @Test void throwsExceptionAboutSettlingPeekedMessagesWithNullLockToken() { final ReceiverOptions options = createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, false); ServiceBusReceiverAsyncClient client = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, options, connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); when(receivedMessage.getLockToken()).thenReturn(null); try { StepVerifier.create(client.complete(receivedMessage)) .expectError(UnsupportedOperationException.class) .verify(); } finally { client.close(); } } /** * Verifies that this peek batch of messages. */ @Test void peekMessages() { final int numberOfEvents = 2; when(managementNode.peek(0, null, null, numberOfEvents)) .thenReturn(Flux.fromArray(new ServiceBusReceivedMessage[]{receivedMessage, receivedMessage2})); StepVerifier.create(receiver.peekMessages(numberOfEvents)) .expectNextCount(numberOfEvents) .verifyComplete(); } /** * Verifies that this peek batch of messages. */ @Test void peekMessagesEmptyEntity() { final int numberOfEvents = 2; when(managementNode.peek(0, null, null, numberOfEvents)) .thenReturn(Flux.fromIterable(Collections.emptyList())); StepVerifier.create(receiver.peekMessages(numberOfEvents)) .verifyComplete(); } /** * Verifies that this peek batch of messages from a sequence Number. */ @Test void peekBatchWithSequenceNumberMessages() { final int numberOfEvents = 2; final int fromSequenceNumber = 10; when(managementNode.peek(fromSequenceNumber, null, null, numberOfEvents)) .thenReturn(Flux.fromArray(new ServiceBusReceivedMessage[]{receivedMessage, receivedMessage2})); StepVerifier.create(receiver.peekMessages(numberOfEvents, fromSequenceNumber)) .expectNext(receivedMessage, receivedMessage2) .verifyComplete(); } /** * Verifies that we can deadletter a message with an error and description. */ @Test void deadLetterWithDescription() { final String lockToken1 = UUID.randomUUID().toString(); final String description = "some-dead-letter-description"; final String reason = "dead-letter-reason"; final Map<String, Object> propertiesToModify = new HashMap<>(); propertiesToModify.put("something", true); final DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setDeadLetterReason(reason) .setDeadLetterErrorDescription(description) .setPropertiesToModify(propertiesToModify); final OffsetDateTime expiration = OffsetDateTime.now().plus(Duration.ofMinutes(5)); final MessageWithLockToken message = mock(MessageWithLockToken.class); when(messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage); when(receivedMessage.getLockToken()).thenReturn(lockToken1); when(receivedMessage.getLockedUntil()).thenReturn(expiration); when(amqpReceiveLink.updateDisposition(eq(lockToken1), argThat(e -> e.getType() == DeliveryStateType.Rejected))).thenReturn(Mono.empty()); StepVerifier.create(receiver.receiveMessages() .take(1) .flatMap(receivedMessage -> receiver.deadLetter(receivedMessage, deadLetterOptions))) .then(() -> messageSink.next(message)) .expectNext() .verifyComplete(); verify(amqpReceiveLink).updateDisposition(eq(lockToken1), isA(Rejected.class)); } /** * Verifies that error source is populated when any error happened while renewing lock. */ @Test void errorSourceOnRenewMessageLock() { final Duration maxDuration = Duration.ofSeconds(8); final String lockToken = "some-token"; when(receivedMessage.getLockToken()).thenReturn(lockToken); when(receivedMessage.getContext()).thenReturn(Context.NONE); when(managementNode.renewMessageLock(lockToken, null)) .thenReturn(Mono.error(new AzureException("some error occurred."))); final ReceiverOptions receiverOptions = createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, true); final ServiceBusReceiverAsyncClient receiver2 = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, receiverOptions, connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); StepVerifier.create(receiver2.renewMessageLock(receivedMessage, maxDuration)) .verifyErrorSatisfies(throwable -> { Assertions.assertTrue(throwable instanceof ServiceBusException); final ServiceBusErrorSource actual = ((ServiceBusException) throwable).getErrorSource(); Assertions.assertEquals(ServiceBusErrorSource.RENEW_LOCK, actual); }); verify(managementNode, times(1)).renewMessageLock(lockToken, null); } /** * Verifies that error source is populated when any error happened while renewing lock. */ @Test /** * Verifies that error source is populated when there is no autoComplete. */ @ParameterizedTest @MethodSource void errorSourceNoneOnSettlement(DispositionStatus dispositionStatus, DeliveryStateType expectedDeliveryState, ServiceBusErrorSource errorSource) { final UUID lockTokenUuid = UUID.randomUUID(); final String lockToken1 = lockTokenUuid.toString(); final MessageWithLockToken message = mock(MessageWithLockToken.class); when(receivedMessage.getLockToken()).thenReturn(lockToken1); when(messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage); when(amqpReceiveLink.updateDisposition(eq(lockToken1), argThat(e -> e.getType() == expectedDeliveryState))) .thenReturn(Mono.error(new AzureException("some error occurred."))); StepVerifier.create(receiver.receiveMessages().take(1) .flatMap(receivedMessage -> { final Mono<Void> operation; switch (dispositionStatus) { case ABANDONED: operation = receiver.abandon(receivedMessage); break; case COMPLETED: operation = receiver.complete(receivedMessage); break; default: throw new IllegalArgumentException("Unrecognized operation: " + dispositionStatus); } return operation; }) ) .then(() -> messageSink.next(message)) .expectNext() .verifyErrorSatisfies(throwable -> { Assertions.assertTrue(throwable instanceof ServiceBusException); final ServiceBusErrorSource actual = ((ServiceBusException) throwable).getErrorSource(); Assertions.assertEquals(errorSource, actual); }); verify(amqpReceiveLink).updateDisposition(eq(lockToken1), any(DeliveryState.class)); } /** * Ensure that we throw right error source when there is any issue during autocomplete. Error source should be * {@link ServiceBusErrorSource */ @Test void errorSourceAutoCompleteMessage() { final int numberOfEvents = 2; final int messagesToReceive = 1; final List<Message> messages = getMessages(); final String lockToken = UUID.randomUUID().toString(); final ReceiverOptions receiverOptions = createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, true); final ServiceBusReceiverAsyncClient receiver2 = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, receiverOptions, connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); when(receivedMessage.getLockToken()).thenReturn(lockToken); when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class))) .thenReturn(receivedMessage); when(amqpReceiveLink.updateDisposition(lockToken, Accepted.getInstance())).thenReturn(Mono.error(new AmqpException(false, AmqpErrorCondition.MESSAGE_LOCK_LOST, "some error occurred.", null))); try { StepVerifier.create(receiver2.receiveMessages().take(numberOfEvents)) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(messagesToReceive) .verifyErrorSatisfies(throwable -> { Assertions.assertTrue(throwable instanceof ServiceBusException); ServiceBusException serviceBusException = (ServiceBusException) throwable; final ServiceBusErrorSource actual = serviceBusException.getErrorSource(); Assertions.assertEquals(ServiceBusErrorSource.COMPLETE, actual); Assertions.assertEquals(ServiceBusFailureReason.MESSAGE_LOCK_LOST, serviceBusException.getReason()); }); } finally { receiver2.close(); } verify(amqpReceiveLink, atLeast(messagesToReceive)).updateDisposition(lockToken, Accepted.getInstance()); } /** * Verifies that error source is populated when there is any error during receiving of message. */ @Test void errorSourceOnReceiveMessage() { final String lockToken = UUID.randomUUID().toString(); final OffsetDateTime expiration = OffsetDateTime.now().plus(Duration.ofMinutes(5)); final MessageWithLockToken message = mock(MessageWithLockToken.class); when(messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage); when(receivedMessage.getLockToken()).thenReturn(lockToken); when(receivedMessage.getLockedUntil()).thenReturn(expiration); final ReceiverOptions receiverOptions = createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, true); final ServiceBusReceiverAsyncClient receiver2 = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, receiverOptions, connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); when(connection.createReceiveLink(anyString(), anyString(), any(ServiceBusReceiveMode.class), any(), any(MessagingEntityType.class), anyString())).thenReturn(Mono.error(new AzureException("some receive link Error."))); StepVerifier.create(receiver2.receiveMessages().take(1)) .verifyErrorSatisfies(throwable -> { Assertions.assertTrue(throwable instanceof ServiceBusException); final ServiceBusErrorSource actual = ((ServiceBusException) throwable).getErrorSource(); Assertions.assertEquals(ServiceBusErrorSource.RECEIVE, actual); }); verify(amqpReceiveLink, never()).updateDisposition(eq(lockToken), any(DeliveryState.class)); } /** * Verifies that the user can complete settlement methods on received message. */ @ParameterizedTest @EnumSource(DispositionStatus.class) void settleMessageOnManagement(DispositionStatus dispositionStatus) { final String lockToken1 = UUID.randomUUID().toString(); final String lockToken2 = UUID.randomUUID().toString(); final OffsetDateTime expiration = OffsetDateTime.now().plus(Duration.ofMinutes(5)); final long sequenceNumber = 10L; final long sequenceNumber2 = 15L; final MessageWithLockToken message = mock(MessageWithLockToken.class); final MessageWithLockToken message2 = mock(MessageWithLockToken.class); when(messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage); when(messageSerializer.deserialize(message2, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage2); when(receivedMessage.getLockToken()).thenReturn(lockToken1); when(receivedMessage.getLockedUntil()).thenReturn(expiration); when(receivedMessage2.getLockToken()).thenReturn(lockToken2); when(receivedMessage2.getLockedUntil()).thenReturn(expiration); when(connection.getManagementNode(eq(ENTITY_PATH), eq(ENTITY_TYPE))) .thenReturn(Mono.just(managementNode)); when(managementNode.receiveDeferredMessages(eq(ServiceBusReceiveMode.PEEK_LOCK), isNull(), isNull(), argThat(arg -> { boolean foundFirst = false; boolean foundSecond = false; for (Long seq : arg) { if (!foundFirst && sequenceNumber == seq) { foundFirst = true; } else if (!foundSecond && sequenceNumber2 == seq) { foundSecond = true; } } return foundFirst && foundSecond; }))) .thenReturn(Flux.just(receivedMessage, receivedMessage2)); when(managementNode.updateDisposition(lockToken1, dispositionStatus, null, null, null, null, null, null)) .thenReturn(Mono.empty()); when(managementNode.updateDisposition(lockToken2, dispositionStatus, null, null, null, null, null, null)) .thenReturn(Mono.empty()); StepVerifier.create(receiver.receiveDeferredMessages(Arrays.asList(sequenceNumber, sequenceNumber2))) .expectNext(receivedMessage, receivedMessage2) .verifyComplete(); final Mono<Void> operation; switch (dispositionStatus) { case DEFERRED: operation = receiver.defer(receivedMessage); break; case ABANDONED: operation = receiver.abandon(receivedMessage); break; case COMPLETED: operation = receiver.complete(receivedMessage); break; case SUSPENDED: operation = receiver.deadLetter(receivedMessage); break; case RELEASED: operation = receiver.release(receivedMessage); break; default: throw new IllegalArgumentException("Unrecognized operation: " + dispositionStatus); } StepVerifier.create(operation) .verifyComplete(); verify(managementNode).updateDisposition(lockToken1, dispositionStatus, null, null, null, null, null, null); verify(managementNode, never()).updateDisposition(lockToken2, dispositionStatus, null, null, null, null, null, null); } /** * Verifies that this receive deferred one messages from a sequence Number. */ @Test void receiveDeferredWithSequenceOneMessage() { final int fromSequenceNumber = 10; final ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class); when(managementNode.receiveDeferredMessages(any(), any(), any(), any())).thenReturn(Flux.just(receivedMessage)); StepVerifier.create(receiver.receiveDeferredMessage(fromSequenceNumber)) .expectNext(receivedMessage) .verifyComplete(); } /** * Verifies that this receive deferred messages from a sequence Number. */ @Test void receiveDeferredBatchFromSequenceNumber() { final long fromSequenceNumber1 = 10; final long fromSequenceNumber2 = 11; when(managementNode.receiveDeferredMessages(any(), any(), any(), any())) .thenReturn(Flux.fromArray(new ServiceBusReceivedMessage[]{receivedMessage, receivedMessage2})); StepVerifier.create(receiver.receiveDeferredMessages(Arrays.asList(fromSequenceNumber1, fromSequenceNumber2))) .expectNext(receivedMessage) .expectNext(receivedMessage2) .verifyComplete(); } /** * Verifies that the onClientClose is called. */ @Test void callsClientClose() { receiver.close(); verify(onClientClose).run(); } /** * Verifies that the onClientClose is only called once. */ @Test void callsClientCloseOnce() { receiver.close(); receiver.close(); verify(onClientClose).run(); } /** * Verifies that managementNodeLocks was closed. */ @Test void callsManagementNodeLocksCloseWhenClientIsClosed() { Assertions.assertFalse(receiver.isManagementNodeLocksClosed()); receiver.close(); Assertions.assertTrue(receiver.isManagementNodeLocksClosed()); } /** * Verifies that renewalContainer was closed. */ @Test void callsRenewalContainerCloseWhenClientIsClosed() { Assertions.assertFalse(receiver.isRenewalContainerClosed()); receiver.close(); Assertions.assertTrue(receiver.isRenewalContainerClosed()); } /** * Tests that invalid options throws and null options. */ @Test void receiveIllegalOptions() { ServiceBusReceiverClientBuilder builder = new ServiceBusClientBuilder() .connectionString(NAMESPACE_CONNECTION_STRING) .receiver() .topicName("baz").subscriptionName("bar") .receiveMode(ServiceBusReceiveMode.PEEK_LOCK); Assertions.assertThrows(IllegalArgumentException.class, () -> builder.prefetchCount(-1)); } @Test void topicCorrectEntityPath() { final String topicName = "foo"; final String subscriptionName = "bar"; final String entityPath = String.join("/", topicName, "subscriptions", subscriptionName); final ServiceBusReceiverAsyncClient receiver = new ServiceBusClientBuilder() .connectionString(NAMESPACE_CONNECTION_STRING) .receiver() .topicName(topicName) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .buildAsyncClient(); final String actual = receiver.getEntityPath(); final String actualNamespace = receiver.getFullyQualifiedNamespace(); Assertions.assertEquals(entityPath, actual); Assertions.assertEquals(NAMESPACE, actualNamespace); } /** * Verifies that client can call multiple receiveMessages on same receiver instance. */ @Test void canPerformMultipleReceive() { final int numberOfEvents = 1; final List<Message> messages = getMessages(); ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class); when(receivedMessage.getLockedUntil()).thenReturn(OffsetDateTime.now()); when(receivedMessage.getLockToken()).thenReturn(UUID.randomUUID().toString()); when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class))) .thenReturn(receivedMessage); StepVerifier.create(receiver.receiveMessages().take(numberOfEvents)) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(numberOfEvents) .verifyComplete(); verify(amqpReceiveLink, atMost(numberOfEvents + 1)).addCredits(PREFETCH); } /** * Cannot get session state for non-session receiver. */ @Test void cannotPerformGetSessionState() { StepVerifier.create(receiver.getSessionState()) .expectError(IllegalStateException.class) .verify(); } /** * Cannot get session state for non-session receiver. */ @Test void cannotPerformSetSessionState() { final String sessionId = "a-session-id"; final byte[] sessionState = new byte[]{10, 11, 8}; StepVerifier.create(receiver.setSessionState(sessionState)) .expectError(IllegalStateException.class) .verify(); } /** * Cannot get session state for non-session receiver. */ @Test void cannotPerformRenewSessionLock() { StepVerifier.create(receiver.renewSessionLock()) .expectError(IllegalStateException.class) .verify(); } /** * Verifies that we can get a session state. */ @SuppressWarnings("unchecked") @Test void getSessionState() { final byte[] bytes = new byte[]{95, 11, 54, 10}; ServiceBusReceiverAsyncClient mySessionReceiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNamedSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, CLEANUP_INTERVAL, false, SESSION_ID), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, mock(ServiceBusSessionManager.class)); when(managementNode.getSessionState(SESSION_ID, null)) .thenReturn(Mono.just(bytes)); StepVerifier.create(mySessionReceiver.getSessionState()) .expectNext(bytes) .expectComplete() .verify(); } /** * Verifies that we can set a session state. */ @Test void setSessionState() { final byte[] bytes = new byte[]{95, 11, 54, 10}; when(managementNode.setSessionState(SESSION_ID, bytes, null)).thenReturn(Mono.empty()); StepVerifier.create(sessionReceiver.setSessionState(bytes)) .expectComplete() .verify(); } /** * Get null session id for non-session receiver and gets valid session id for a session receiver. */ @Test void getSessionIdTests() { Assertions.assertNull(receiver.getSessionId(), "Non-null session Id for a non-session receiver"); Assertions.assertEquals(SESSION_ID, sessionReceiver.getSessionId()); } /** * Verifies that we can renew a session state. */ @Test void renewSessionLock() { final OffsetDateTime expiry = Instant.ofEpochSecond(1588011761L).atOffset(ZoneOffset.UTC); when(managementNode.renewSessionLock(SESSION_ID, null)).thenReturn(Mono.just(expiry)); StepVerifier.create(sessionReceiver.renewSessionLock()) .expectNext(expiry) .expectComplete() .verify(); } /** * Verifies that we cannot renew a message lock when using a session receiver. */ @Test void cannotRenewMessageLockInSession() { when(receivedMessage.getLockToken()).thenReturn("lock-token"); when(receivedMessage.getSessionId()).thenReturn("fo"); StepVerifier.create(sessionReceiver.renewMessageLock(receivedMessage)) .expectError(IllegalStateException.class) .verify(); } /** * Verifies that we can auto-renew a message lock. */ @Test void autoRenewMessageLock() { final Duration maxDuration = Duration.ofSeconds(8); final Duration renewalPeriod = Duration.ofSeconds(3); final UUID lockTokenUUID = UUID.randomUUID(); final String lockToken = lockTokenUUID.toString(); final ServiceBusReceivedMessage message = new ServiceBusReceivedMessage(BinaryData.fromString("foo")); message.setLockToken(lockTokenUUID); final int atMost = 6; final Duration totalSleepPeriod = maxDuration.plusMillis(500); when(managementNode.renewMessageLock(lockToken, null)) .thenReturn(Mono.fromCallable(() -> OffsetDateTime.now().plus(renewalPeriod))); StepVerifier.create(receiver.renewMessageLock(message, maxDuration)) .thenAwait(totalSleepPeriod) .then(() -> LOGGER.info("Finished renewals for first sleep.")) .expectComplete() .verify(Duration.ofSeconds(5)); verify(managementNode, Mockito.atMost(atMost)).renewMessageLock(lockToken, null); } /** * Verifies that it errors when we try a null lock token. */ @Test void autoRenewMessageLockErrorNull() { final Duration maxDuration = Duration.ofSeconds(8); final Duration renewalPeriod = Duration.ofSeconds(3); when(receivedMessage.getLockToken()).thenReturn(null); when(managementNode.renewMessageLock(anyString(), isNull())) .thenReturn(Mono.fromCallable(() -> OffsetDateTime.now().plus(renewalPeriod))); StepVerifier.create(receiver.renewMessageLock(receivedMessage, maxDuration)) .expectError(NullPointerException.class) .verify(); verify(managementNode, never()).renewMessageLock(anyString(), isNull()); } /** * Verifies that it errors when we try an empty string lock token. */ @Test void autoRenewMessageLockErrorEmptyString() { final Duration maxDuration = Duration.ofSeconds(8); final Duration renewalPeriod = Duration.ofSeconds(3); final String lockToken = ""; when(receivedMessage.getLockToken()).thenReturn(""); when(managementNode.renewMessageLock(anyString(), isNull())) .thenReturn(Mono.fromCallable(() -> OffsetDateTime.now().plus(renewalPeriod))); StepVerifier.create(receiver.renewMessageLock(receivedMessage, maxDuration)) .expectError(IllegalArgumentException.class) .verify(); verify(managementNode, never()).renewMessageLock(anyString(), isNull()); } /** * Verifies that we can auto-renew a session lock. */ @Test void autoRenewSessionLock() { final Duration maxDuration = Duration.ofSeconds(8); final Duration renewalPeriod = Duration.ofSeconds(3); final String sessionId = "some-token"; final int atMost = 6; final Duration totalSleepPeriod = maxDuration.plusMillis(500); when(managementNode.renewSessionLock(SESSION_ID, null)) .thenReturn(Mono.fromCallable(() -> OffsetDateTime.now().plus(renewalPeriod))); StepVerifier.create(sessionReceiver.renewSessionLock(maxDuration)) .thenAwait(totalSleepPeriod) .then(() -> LOGGER.info("Finished renewals for first sleep.")) .expectComplete() .verify(Duration.ofSeconds(5)); verify(managementNode, Mockito.atMost(atMost)).renewSessionLock(sessionId, null); } /** * Verifies that it errors if session renewal is tried on session unaware receiver. */ @Test void cannotRenewSessionLockForNonSessionReceiver() { StepVerifier.create(receiver.renewSessionLock()) .expectError(IllegalStateException.class) .verify(); } @Test void autoCompleteMessage() { final int numberOfEvents = 3; final List<Message> messages = getMessages(); final String lockToken = UUID.randomUUID().toString(); final ReceiverOptions receiverOptions = createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, true); final ServiceBusReceiverAsyncClient receiver2 = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, receiverOptions, connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); when(receivedMessage.getLockToken()).thenReturn(lockToken); when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class))) .thenReturn(receivedMessage); when(amqpReceiveLink.updateDisposition(lockToken, Accepted.getInstance())).thenReturn(Mono.empty()); try { StepVerifier.create(receiver2.receiveMessages().take(numberOfEvents)) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(numberOfEvents) .verifyComplete(); } finally { receiver2.close(); } verify(amqpReceiveLink, times(numberOfEvents)).updateDisposition(lockToken, Accepted.getInstance()); } @Test void autoCompleteMessageSessionReceiver() { final int numberOfEvents = 3; final List<Message> messages = getMessages(); final String lockToken = "token1"; final String lockToken2 = "token2"; final String lockToken3 = "token3"; final ServiceBusSessionManager sessionManager = mock(ServiceBusSessionManager.class); final ReceiverOptions receiverOptions = createNamedSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, true, SESSION_ID); final ServiceBusReceiverAsyncClient sessionReceiver2 = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, receiverOptions, connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, sessionManager); final ServiceBusReceivedMessage receivedMessage3 = mock(ServiceBusReceivedMessage.class); when(receivedMessage.getLockToken()).thenReturn(lockToken); when(receivedMessage2.getLockToken()).thenReturn(lockToken2); when(receivedMessage3.getLockToken()).thenReturn(lockToken3); final List<ServiceBusReceivedMessage> sessionMessages = new ArrayList<>(); sessionMessages.add(receivedMessage); sessionMessages.add(receivedMessage2); sessionMessages.add(receivedMessage3); when(sessionManager.receive()).thenReturn(Flux.fromIterable(sessionMessages).map(ServiceBusMessageContext::new)); when(sessionManager.updateDisposition(eq(lockToken), any(), eq(DispositionStatus.COMPLETED), any(), any(), any(), any())).thenReturn(Mono.empty()); when(sessionManager.updateDisposition(eq(lockToken2), any(), eq(DispositionStatus.COMPLETED), any(), any(), any(), any())).thenReturn(Mono.empty()); when(sessionManager.updateDisposition(eq(lockToken3), any(), eq(DispositionStatus.COMPLETED), any(), any(), any(), any())).thenReturn(Mono.empty()); try { StepVerifier.create(sessionReceiver2.receiveMessages().take(numberOfEvents)) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(numberOfEvents) .verifyComplete(); } finally { sessionReceiver2.close(); } verify(sessionManager).updateDisposition(eq(lockToken), any(), any(), any(), any(), any(), any()); verify(sessionManager).updateDisposition(eq(lockToken2), any(), any(), any(), any(), any(), any()); verify(sessionManager).updateDisposition(eq(lockToken3), any(), any(), any(), any(), any(), any()); } @Test void receiveMessagesReportsMetricsAsyncInstr() { final List<Message> messages = getMessages(); TestMeter meter = new TestMeter(); ServiceBusReceiverInstrumentation instrumentation = new ServiceBusReceiverInstrumentation(null, meter, NAMESPACE, ENTITY_PATH, SUBSCRIPTION_NAME, false); receiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, false), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); ServiceBusReceivedMessage receivedMessage1 = mockReceivedMessage(Instant.now().minusSeconds(1000)); ServiceBusReceivedMessage receivedMessage2 = mockReceivedMessage(Instant.now().minusSeconds(500)); when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class))) .thenReturn(receivedMessage1, receivedMessage2); StepVerifier.create(receiver.receiveMessages().take(2)) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(2) .verifyComplete(); TestHistogram receiverLag = meter.getHistograms().get("messaging.servicebus.receiver.lag"); assertNotNull(receiverLag); assertEquals(2, receiverLag.getMeasurements().size()); TestMeasurement<Double> measurement1 = receiverLag.getMeasurements().get(0); TestMeasurement<Double> measurement2 = receiverLag.getMeasurements().get(1); assertEquals(1000d, measurement1.getValue(), 10d); assertEquals(500d, measurement2.getValue(), 10d); Map<String, Object> attributes1 = measurement1.getAttributes(); Map<String, Object> attributes2 = measurement2.getAttributes(); assertEquals(3, attributes1.size()); assertCommonMetricAttributes(attributes1, SUBSCRIPTION_NAME); assertEquals(3, attributes2.size()); assertCommonMetricAttributes(attributes2, SUBSCRIPTION_NAME); } @ParameterizedTest() @EnumSource(DispositionStatus.class) void settlementMessagesReportsMetrics(DispositionStatus status) { final List<Message> messages = getMessages(); TestMeter meter = new TestMeter(); ServiceBusReceiverInstrumentation instrumentation = new ServiceBusReceiverInstrumentation(null, meter, NAMESPACE, ENTITY_PATH, SUBSCRIPTION_NAME, false); receiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, false), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); when(receivedMessage.getLockToken()).thenReturn("mylockToken"); when(receivedMessage.getSequenceNumber()).thenReturn(42L); when(receivedMessage.getContext()).thenReturn(Context.NONE); when(managementNode.updateDisposition(any(), any(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull())).thenReturn(Mono.empty()); Mono<Void> settle; switch (status) { case COMPLETED: { settle = receiver.complete(receivedMessage); break; } case ABANDONED: { settle = receiver.abandon(receivedMessage); break; } case DEFERRED: { settle = receiver.defer(receivedMessage); break; } case SUSPENDED: { settle = receiver.deadLetter(receivedMessage); break; } default: { return; } } StepVerifier.create(settle).verifyComplete(); TestHistogram settlementDuration = meter.getHistograms().get("messaging.servicebus.settlement.request.duration"); assertNotNull(settlementDuration); assertEquals(1, settlementDuration.getMeasurements().size()); TestMeasurement<Double> measurement = settlementDuration.getMeasurements().get(0); assertEquals(5000d, measurement.getValue(), 5000d); Map<String, Object> attributes = measurement.getAttributes(); assertEquals(5, attributes.size()); assertCommonMetricAttributes(attributes, SUBSCRIPTION_NAME); assertEquals(status.getValue(), attributes.get("dispositionStatus")); assertEquals("ok", attributes.get("status")); TestGauge settlementSeqNo = meter.getGauges().get("messaging.servicebus.settlement.sequence_number"); assertEquals(10, settlementSeqNo.getSubscriptions().size()); settlementSeqNo.getSubscriptions().forEach(s -> s.measure()); boolean measurementFound = false; for (TestGauge.Subscription subs : settlementSeqNo.getSubscriptions()) { assertEquals(1, subs.getMeasurements().size()); TestMeasurement<Long> seqNoMeasurement = subs.getMeasurements().get(0); if (seqNoMeasurement.getAttributes().get("dispositionStatus").equals(status.getValue()) && seqNoMeasurement.getAttributes().get("status").equals("ok")) { measurementFound = true; assertEquals(42, seqNoMeasurement.getValue()); assertEquals(5, seqNoMeasurement.getAttributes().size()); assertCommonMetricAttributes(seqNoMeasurement.getAttributes(), SUBSCRIPTION_NAME); } else { assertEquals(0, seqNoMeasurement.getValue()); assertEquals(5, seqNoMeasurement.getAttributes().size()); assertCommonMetricAttributes(seqNoMeasurement.getAttributes(), SUBSCRIPTION_NAME); } } assertTrue(measurementFound); } @Test void receiveWithTracesAndMetrics() { final List<Message> messages = getMessages(); TestMeter meter = new TestMeter(); Tracer tracer = mock(Tracer.class); when(tracer.isEnabled()).thenReturn(true); ServiceBusReceiverInstrumentation instrumentation = new ServiceBusReceiverInstrumentation(tracer, meter, NAMESPACE, ENTITY_PATH, SUBSCRIPTION_NAME, false); receiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, false), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); Context spanReceive1 = new Context("marker1", true); Context spanReceive2 = new Context("marker2", true); Context spanSettle = new Context("marker3", true); when(tracer.start(eq("ServiceBus.process"), any(StartSpanOptions.class), any(Context.class))).thenReturn(spanReceive1, spanReceive2); when(tracer.start(eq("ServiceBus.complete"), any(StartSpanOptions.class), any(Context.class))).thenReturn(spanSettle); when(receivedMessage.getLockToken()).thenReturn("mylockToken"); when(receivedMessage.getSequenceNumber()).thenReturn(42L); when(receivedMessage.getContext()).thenReturn(Context.NONE); when(receivedMessage2.getLockToken()).thenReturn("mylockToken"); when(receivedMessage2.getSequenceNumber()).thenReturn(43L); when(receivedMessage2.getContext()).thenReturn(Context.NONE); when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class))) .thenReturn(receivedMessage, receivedMessage2); when(managementNode.updateDisposition(any(), any(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull())).thenReturn(Mono.empty()); when(amqpReceiveLink.updateDisposition(any(), any())).thenReturn(Mono.empty()); StepVerifier.create(receiver.receiveMessages().take(2).flatMap(msg -> receiver.complete(msg))) .then(() -> messages.forEach(m -> messageSink.next(m))) .verifyComplete(); TestHistogram receiverLag = meter.getHistograms().get("messaging.servicebus.receiver.lag"); assertEquals(2, receiverLag.getMeasurements().size()); TestMeasurement<Double> measurement1 = receiverLag.getMeasurements().get(0); TestMeasurement<Double> measurement2 = receiverLag.getMeasurements().get(1); assertEquals(spanReceive1, measurement1.getContext()); assertEquals(spanReceive2, measurement2.getContext()); TestHistogram settlementDuration = meter.getHistograms().get("messaging.servicebus.settlement.request.duration"); assertEquals(spanSettle, settlementDuration.getMeasurements().get(0).getContext()); TestGauge settlementSeqNo = meter.getGauges().get("messaging.servicebus.settlement.sequence_number"); TestGauge.Subscription subs = settlementSeqNo.getSubscriptions().get(0); subs.measure(); assertSame(Context.NONE, subs.getMeasurements().get(0).getContext()); } @Test void receiveMessageNegativeLagReportsMetricsAsyncInstr() { final List<Message> messages = getMessages(); TestMeter meter = new TestMeter(); ServiceBusReceiverInstrumentation instrumentation = new ServiceBusReceiverInstrumentation(null, meter, NAMESPACE, ENTITY_PATH, null, false); receiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, false), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); ServiceBusReceivedMessage receivedMessage1 = mockReceivedMessage(Instant.now().plusSeconds(1000)); when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class))) .thenReturn(receivedMessage1); StepVerifier.create(receiver.receiveMessages().take(1)) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(1) .verifyComplete(); TestHistogram receiverLag = meter.getHistograms().get("messaging.servicebus.receiver.lag"); assertEquals(1, receiverLag.getMeasurements().size()); TestMeasurement<Double> measurement = receiverLag.getMeasurements().get(0); assertEquals(0d, measurement.getValue(), 1d); Map<String, Object> attributes = measurement.getAttributes(); assertEquals(2, attributes.size()); assertCommonMetricAttributes(attributes, null); } @Test void receiveMessageNegativeLagReportsMetricsSyncInstr() { final List<Message> messages = getMessages(); TestMeter meter = new TestMeter(); ServiceBusReceiverInstrumentation instrumentation = new ServiceBusReceiverInstrumentation(null, meter, NAMESPACE, ENTITY_PATH, null, true); receiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, createNonSessionOptions(ServiceBusReceiveMode.PEEK_LOCK, PREFETCH, null, false), connectionProcessor, CLEANUP_INTERVAL, instrumentation, messageSerializer, onClientClose, CLIENT_IDENTIFIER); ServiceBusReceivedMessage receivedMessage1 = mockReceivedMessage(Instant.now()); when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class))) .thenReturn(receivedMessage1); StepVerifier.create(receiver.receiveMessages().take(1)) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(1) .verifyComplete(); TestHistogram receiverLag = meter.getHistograms().get("messaging.servicebus.receiver.lag"); assertEquals(1, receiverLag.getMeasurements().size()); TestMeasurement<Double> measurement = receiverLag.getMeasurements().get(0); Map<String, Object> attributes = measurement.getAttributes(); assertEquals(2, attributes.size()); assertCommonMetricAttributes(attributes, null); } private ServiceBusReceivedMessage mockReceivedMessage(Instant enqueuedTime) { ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class); when(receivedMessage.getLockedUntil()).thenReturn(OffsetDateTime.now()); when(receivedMessage.getLockToken()).thenReturn(UUID.randomUUID().toString()); when(receivedMessage.getEnqueuedTime()).thenReturn(enqueuedTime.atOffset(ZoneOffset.UTC)); return receivedMessage; } private List<Message> getMessages() { final Map<String, String> map = Collections.singletonMap("SAMPLE_HEADER", "foo"); return IntStream.range(0, 10) .mapToObj(index -> getMessage(PAYLOAD_BYTES, messageTrackingUUID, map)) .collect(Collectors.toList()); } private static Stream<Arguments> errorSourceNoneOnSettlement() { return Stream.of( Arguments.of(DispositionStatus.COMPLETED, DeliveryStateType.Accepted, ServiceBusErrorSource.COMPLETE), Arguments.of(DispositionStatus.ABANDONED, DeliveryStateType.Modified, ServiceBusErrorSource.ABANDON)); } private void assertCommonMetricAttributes(Map<String, Object> attributes, String subscriptionName) { assertEquals(NAMESPACE, attributes.get("hostName")); assertEquals(ENTITY_PATH, attributes.get("entityName")); assertEquals(subscriptionName, attributes.get("subscriptionName")); } }
The cloning logic below should copy the isChained status to the cloned object.
public IdentityClientOptions clone() { IdentityClientOptions clone = new IdentityClientOptions() .setAdditionallyAllowedTenants(this.additionallyAllowedTenants) .setAllowUnencryptedCache(this.allowUnencryptedCache) .setHttpClient(this.httpClient) .setAuthenticationRecord(this.authenticationRecord) .setExecutorService(this.executorService) .setIdentityLogOptionsImpl(this.identityLogOptionsImpl) .setTokenCacheOptions(this.tokenCachePersistenceOptions) .setRetryTimeout(this.retryTimeout) .setRegionalAuthority(this.regionalAuthority) .setHttpPipeline(this.httpPipeline) .setIncludeX5c(this.includeX5c) .setProxyOptions(this.proxyOptions) .setMaxRetry(this.maxRetry) .setIntelliJKeePassDatabasePath(this.keePassDatabasePath) .setAuthorityHost(this.authorityHost) .setImdsAuthorityHost(this.imdsAuthorityHost) .setCp1Disabled(this.cp1Disabled) .setMultiTenantAuthDisabled(this.multiTenantAuthDisabled) .setUserAssertion(this.userAssertion) .setConfigurationStore(this.configuration) .setPersistenceCache(this.sharedTokenCacheEnabled) .setClientOptions(this.clientOptions) .setHttpLogOptions(this.httpLogOptions) .setRetryOptions(this.retryOptions) .setRetryPolicy(this.retryPolicy) .setPerCallPolicies(this.perCallPolicies) .setPerRetryPolicies(this.perRetryPolicies); if (!isInstanceDiscoveryEnabled()) { clone.disableInstanceDiscovery(); } return clone; }
IdentityClientOptions clone = new IdentityClientOptions()
public IdentityClientOptions clone() { IdentityClientOptions clone = new IdentityClientOptions() .setAdditionallyAllowedTenants(this.additionallyAllowedTenants) .setAllowUnencryptedCache(this.allowUnencryptedCache) .setHttpClient(this.httpClient) .setAuthenticationRecord(this.authenticationRecord) .setExecutorService(this.executorService) .setIdentityLogOptionsImpl(this.identityLogOptionsImpl) .setTokenCacheOptions(this.tokenCachePersistenceOptions) .setRetryTimeout(this.retryTimeout) .setRegionalAuthority(this.regionalAuthority) .setHttpPipeline(this.httpPipeline) .setIncludeX5c(this.includeX5c) .setProxyOptions(this.proxyOptions) .setMaxRetry(this.maxRetry) .setIntelliJKeePassDatabasePath(this.keePassDatabasePath) .setAuthorityHost(this.authorityHost) .setImdsAuthorityHost(this.imdsAuthorityHost) .setCp1Disabled(this.cp1Disabled) .setMultiTenantAuthDisabled(this.multiTenantAuthDisabled) .setUserAssertion(this.userAssertion) .setConfigurationStore(this.configuration) .setPersistenceCache(this.sharedTokenCacheEnabled) .setClientOptions(this.clientOptions) .setHttpLogOptions(this.httpLogOptions) .setRetryOptions(this.retryOptions) .setRetryPolicy(this.retryPolicy) .setPerCallPolicies(this.perCallPolicies) .setPerRetryPolicies(this.perRetryPolicies) .setChained(this.isChained); if (!isInstanceDiscoveryEnabled()) { clone.disableInstanceDiscovery(); } return clone; }
class IdentityClientOptions implements Cloneable { private static final ClientLogger LOGGER = new ClientLogger(IdentityClientOptions.class); private static final int MAX_RETRY_DEFAULT_LIMIT = 3; public static final String AZURE_IDENTITY_DISABLE_MULTI_TENANT_AUTH = "AZURE_IDENTITY_DISABLE_MULTITENANTAUTH"; public static final String AZURE_POD_IDENTITY_AUTHORITY_HOST = "AZURE_POD_IDENTITY_AUTHORITY_HOST"; private String authorityHost; private String imdsAuthorityHost; private int maxRetry; private Function<Duration, Duration> retryTimeout; private ProxyOptions proxyOptions; private HttpPipeline httpPipeline; private ExecutorService executorService; private HttpClient httpClient; private boolean allowUnencryptedCache; private boolean sharedTokenCacheEnabled; private String keePassDatabasePath; private boolean includeX5c; private AuthenticationRecord authenticationRecord; private TokenCachePersistenceOptions tokenCachePersistenceOptions; private boolean cp1Disabled; private RegionalAuthority regionalAuthority; private UserAssertion userAssertion; private boolean multiTenantAuthDisabled; private Configuration configuration; private IdentityLogOptionsImpl identityLogOptionsImpl; private boolean accountIdentifierLogging; private ManagedIdentityType managedIdentityType; private ManagedIdentityParameters managedIdentityParameters; private Set<String> additionallyAllowedTenants; private ClientOptions clientOptions; private HttpLogOptions httpLogOptions; private RetryOptions retryOptions; private RetryPolicy retryPolicy; private List<HttpPipelinePolicy> perCallPolicies; private List<HttpPipelinePolicy> perRetryPolicies; private boolean instanceDiscovery; private Duration credentialProcessTimeout = Duration.ofSeconds(10); private boolean isChained; /** * Creates an instance of IdentityClientOptions with default settings. */ public IdentityClientOptions() { Configuration configuration = Configuration.getGlobalConfiguration().clone(); loadFromConfiguration(configuration); identityLogOptionsImpl = new IdentityLogOptionsImpl(); maxRetry = MAX_RETRY_DEFAULT_LIMIT; retryTimeout = i -> Duration.ofSeconds((long) Math.pow(2, i.getSeconds() - 1)); perCallPolicies = new ArrayList<>(); perRetryPolicies = new ArrayList<>(); additionallyAllowedTenants = new HashSet<>(); regionalAuthority = RegionalAuthority.fromString( configuration.get(Configuration.PROPERTY_AZURE_REGIONAL_AUTHORITY_NAME)); instanceDiscovery = true; } /** * @return the Azure Active Directory endpoint to acquire tokens. */ public String getAuthorityHost() { return authorityHost; } /** * Specifies the Azure Active Directory endpoint to acquire tokens. * @param authorityHost the Azure Active Directory endpoint * @return IdentityClientOptions */ public IdentityClientOptions setAuthorityHost(String authorityHost) { this.authorityHost = authorityHost; return this; } /** * @return the AKS Pod Authority endpoint to acquire tokens. */ public String getImdsAuthorityHost() { return imdsAuthorityHost; } /** * @return the max number of retries when an authentication request fails. */ public int getMaxRetry() { return maxRetry; } /** * Specifies the max number of retries when an authentication request fails. * @param maxRetry the number of retries * @return IdentityClientOptions */ public IdentityClientOptions setMaxRetry(int maxRetry) { this.maxRetry = maxRetry; return this; } /** * @return a Function to calculate seconds of timeout on every retried request. */ public Function<Duration, Duration> getRetryTimeout() { return retryTimeout; } /** * Specifies a Function to calculate seconds of timeout on every retried request. * @param retryTimeout the Function that returns a timeout in seconds given the number of retry * @return IdentityClientOptions */ public IdentityClientOptions setRetryTimeout(Function<Duration, Duration> retryTimeout) { this.retryTimeout = retryTimeout; return this; } /** * @return the options for proxy configuration. */ public ProxyOptions getProxyOptions() { return proxyOptions; } /** * Specifies the options for proxy configuration. * @param proxyOptions the options for proxy configuration * @return IdentityClientOptions */ public IdentityClientOptions setProxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * @return the HttpPipeline to send all requests */ public HttpPipeline getHttpPipeline() { return httpPipeline; } /** * @return the HttpClient to use for requests */ public HttpClient getHttpClient() { return httpClient; } /** * Specifies the HttpPipeline to send all requests. This setting overrides the others. * @param httpPipeline the HttpPipeline to send all requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpPipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Specifies the ExecutorService to be used to execute the authentication requests. * Developer is responsible for maintaining the lifecycle of the ExecutorService. * * <p> * If this is not configured, the {@link ForkJoinPool * also shared with other application tasks. If the common pool is heavily used for other tasks, authentication * requests might starve and setting up this executor service should be considered. * </p> * * <p> The executor service and can be safely shutdown if the TokenCredential is no longer being used by the * Azure SDK clients and should be shutdown before the application exits. </p> * * @param executorService the executor service to use for executing authentication requests. * @return IdentityClientOptions */ public IdentityClientOptions setExecutorService(ExecutorService executorService) { this.executorService = executorService; return this; } /** * @return the ExecutorService to execute authentication requests. */ public ExecutorService getExecutorService() { return executorService; } /** * Specifies the HttpClient to send use for requests. * @param httpClient the http client to use for requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @param allowUnencryptedCache the flag to indicate if unencrypted persistent cache is allowed for use or not. * @return The updated identity client options. */ public IdentityClientOptions setAllowUnencryptedCache(boolean allowUnencryptedCache) { this.allowUnencryptedCache = allowUnencryptedCache; return this; } public boolean getAllowUnencryptedCache() { return this.allowUnencryptedCache; } /** * Specifies the database to extract IntelliJ cached credentials from. * @param keePassDatabasePath the database to extract intellij credentials from. * @return IdentityClientOptions */ public IdentityClientOptions setIntelliJKeePassDatabasePath(String keePassDatabasePath) { this.keePassDatabasePath = keePassDatabasePath; return this; } /** * Gets if the shared token cache is disabled. * @return if the shared token cache is disabled. */ public boolean isSharedTokenCacheEnabled() { return this.sharedTokenCacheEnabled; } /** * Enables the shared token cache which is disabled by default. If enabled, the client will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return The updated identity client options. */ public IdentityClientOptions enablePersistentCache() { this.sharedTokenCacheEnabled = true; return this; } /* * Get the KeePass database path. * @return the KeePass database path to extract inellij credentials from. */ public String getIntelliJKeePassDatabasePath() { return keePassDatabasePath; } /** * Sets the {@link AuthenticationRecord} captured from a previous authentication. * * @param authenticationRecord The Authentication record to be configured. * * @return An updated instance of this builder with the configured authentication record. */ public IdentityClientOptions setAuthenticationRecord(AuthenticationRecord authenticationRecord) { this.authenticationRecord = authenticationRecord; return this; } /** * Get the status whether x5c claim (public key of the certificate) should be included as part of the authentication * request or not. * @return the status of x5c claim inclusion. */ public boolean isIncludeX5c() { return includeX5c; } /** * Specifies if the x5c claim (public key of the certificate) should be sent as part of the authentication request. * The default value is false. * * @param includeX5c true if the x5c should be sent. Otherwise false * @return The updated identity client options. */ public IdentityClientOptions setIncludeX5c(boolean includeX5c) { this.includeX5c = includeX5c; return this; } /** * Get the configured {@link AuthenticationRecord}. * * @return {@link AuthenticationRecord}. */ public AuthenticationRecord getAuthenticationRecord() { return authenticationRecord; } /** * Specifies the {@link TokenCachePersistenceOptions} to be used for token cache persistence. * * @param tokenCachePersistenceOptions the options configuration * @return the updated identity client options */ public IdentityClientOptions setTokenCacheOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { this.tokenCachePersistenceOptions = tokenCachePersistenceOptions; return this; } /** * Get the configured {@link TokenCachePersistenceOptions} * * @return the {@link TokenCachePersistenceOptions} */ public TokenCachePersistenceOptions getTokenCacheOptions() { return this.tokenCachePersistenceOptions; } /** * Check whether CP1 client capability should be disabled. * * @return the status indicating if CP1 client capability should be disabled. */ public boolean isCp1Disabled() { return this.cp1Disabled; } /** * Gets the regional authority, or null if regional authority should not be used. * @return the regional authority value if specified */ public RegionalAuthority getRegionalAuthority() { return regionalAuthority; } /** * Configure the User Assertion Scope to be used for OnBehalfOf Authentication request. * * @param userAssertion the user assertion access token to be used for On behalf Of authentication flow * @return the updated identity client options */ public IdentityClientOptions userAssertion(String userAssertion) { this.userAssertion = new UserAssertion(userAssertion); return this; } /** * Get the configured {@link UserAssertion} * * @return the configured user assertion scope */ public UserAssertion getUserAssertion() { return this.userAssertion; } /** * Gets the status whether multi tenant auth is disabled or not. * @return the flag indicating if multi tenant is disabled or not. */ public boolean isMultiTenantAuthenticationDisabled() { return multiTenantAuthDisabled; } /** * Disable the multi tenant authentication. * @return the updated identity client options */ public IdentityClientOptions disableMultiTenantAuthentication() { this.multiTenantAuthDisabled = true; return this; } /** * Sets the specified configuration store. * * @param configuration the configuration store to be used to read env variables and/or system properties. * @return the updated identity client options */ public IdentityClientOptions setConfiguration(Configuration configuration) { this.configuration = configuration; loadFromConfiguration(configuration); return this; } /** * Gets the configured configuration store. * * @return the configured {@link Configuration} store. */ public Configuration getConfiguration() { return this.configuration; } /** * Get the configured Identity Log options. * @return the identity log options. */ public IdentityLogOptionsImpl getIdentityLogOptionsImpl() { return identityLogOptionsImpl; } /** * Set the Identity Log options. * @return the identity log options. */ public IdentityClientOptions setIdentityLogOptionsImpl(IdentityLogOptionsImpl identityLogOptionsImpl) { this.identityLogOptionsImpl = identityLogOptionsImpl; return this; } /** * Set the Managed Identity Type * @param managedIdentityType the Managed Identity Type * @return the updated identity client options */ public IdentityClientOptions setManagedIdentityType(ManagedIdentityType managedIdentityType) { this.managedIdentityType = managedIdentityType; return this; } /** * Get the Managed Identity Type * @return the Managed Identity Type */ public ManagedIdentityType getManagedIdentityType() { return managedIdentityType; } /** * Get the Managed Identity parameters * @return the Managed Identity Parameters */ public ManagedIdentityParameters getManagedIdentityParameters() { return managedIdentityParameters; } /** * Configure the managed identity parameters. * * @param managedIdentityParameters the managed identity parameters to use for authentication. * @return the updated identity client options */ public IdentityClientOptions setManagedIdentityParameters(ManagedIdentityParameters managedIdentityParameters) { this.managedIdentityParameters = managedIdentityParameters; return this; } /** * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the application is installed. * * @param additionallyAllowedTenants the additionally allowed Tenants. * @return An updated instance of this builder with the tenant id set as specified. */ @SuppressWarnings("unchecked") public IdentityClientOptions setAdditionallyAllowedTenants(List<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); this.additionallyAllowedTenants.addAll(additionallyAllowedTenants); return this; } /** * Get the Additionally Allowed Tenants. * @return the List containing additionally allowed tenants. */ public Set<String> getAdditionallyAllowedTenants() { return this.additionallyAllowedTenants; } /** * Configure the client options. * @param clientOptions the client options input. * @return the updated client options */ public IdentityClientOptions setClientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Get the configured client options. * @return the client options. */ public ClientOptions getClientOptions() { return this.clientOptions; } /** * Configure the client options. * @param httpLogOptions the Http log options input. * @return the updated client options */ public IdentityClientOptions setHttpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /** * Get the configured Http log options. * @return the Http log options. */ public HttpLogOptions getHttpLogOptions() { return this.httpLogOptions; } /** * Configure the retry options. * @param retryOptions the retry options input. * @return the updated client options */ public IdentityClientOptions setRetryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Get the configured retry options. * @return the retry options. */ public RetryOptions getRetryOptions() { return this.retryOptions; } /** * Configure the retry policy. * @param retryPolicy the retry policy. * @return the updated client options */ public IdentityClientOptions setRetryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Get the configured retry policy. * @return the retry policy. */ public RetryPolicy getRetryPolicy() { return this.retryPolicy; } /** * Add a per call policy. * @param httpPipelinePolicy the http pipeline policy to add. * @return the updated client options */ public IdentityClientOptions addPerCallPolicy(HttpPipelinePolicy httpPipelinePolicy) { this.perCallPolicies.add(httpPipelinePolicy); return this; } /** * Add a per retry policy. * @param httpPipelinePolicy the retry policy to be added. * @return the updated client options */ public IdentityClientOptions addPerRetryPolicy(HttpPipelinePolicy httpPipelinePolicy) { this.perRetryPolicies.add(httpPipelinePolicy); return this; } /** * Get the configured per retry policies. * @return the per retry policies. */ public List<HttpPipelinePolicy> getPerRetryPolicies() { return this.perRetryPolicies; } /** * Get the configured per call policies. * @return the per call policies. */ public List<HttpPipelinePolicy> getPerCallPolicies() { return this.perCallPolicies; } IdentityClientOptions setCp1Disabled(boolean cp1Disabled) { this.cp1Disabled = cp1Disabled; return this; } IdentityClientOptions setMultiTenantAuthDisabled(boolean multiTenantAuthDisabled) { this.multiTenantAuthDisabled = multiTenantAuthDisabled; return this; } IdentityClientOptions setAdditionallyAllowedTenants(Set<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = additionallyAllowedTenants; return this; } /** * Specifies either the specific regional authority, or use {@link RegionalAuthority * * @param regionalAuthority the regional authority * @return the updated identity client options */ IdentityClientOptions setRegionalAuthority(RegionalAuthority regionalAuthority) { this.regionalAuthority = regionalAuthority; return this; } IdentityClientOptions setConfigurationStore(Configuration configuration) { this.configuration = configuration; return this; } IdentityClientOptions setUserAssertion(UserAssertion userAssertion) { this.userAssertion = userAssertion; return this; } IdentityClientOptions setPersistenceCache(boolean persistenceCache) { this.sharedTokenCacheEnabled = persistenceCache; return this; } IdentityClientOptions setImdsAuthorityHost(String imdsAuthorityHost) { this.imdsAuthorityHost = imdsAuthorityHost; return this; } IdentityClientOptions setPerCallPolicies(List<HttpPipelinePolicy> perCallPolicies) { this.perCallPolicies = perCallPolicies; return this; } IdentityClientOptions setPerRetryPolicies(List<HttpPipelinePolicy> perRetryPolicies) { this.perRetryPolicies = perRetryPolicies; return this; } /** * Disables authority validation and instance discovery. * Instance discovery is acquiring metadata about an authority from https: * to validate that authority. This may need to be disabled in private cloud or ADFS scenarios. * * @return the updated client options */ public IdentityClientOptions disableInstanceDiscovery() { this.instanceDiscovery = false; return this; } /** * Gets the instance discovery policy. * @return boolean indicating if instance discovery is enabled. */ public boolean isInstanceDiscoveryEnabled() { return this.instanceDiscovery; } /** * Loads the details from the specified Configuration Store. */ private void loadFromConfiguration(Configuration configuration) { authorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); imdsAuthorityHost = configuration.get(AZURE_POD_IDENTITY_AUTHORITY_HOST, IdentityConstants.DEFAULT_IMDS_ENDPOINT); ValidationUtil.validateAuthHost(authorityHost, LOGGER); cp1Disabled = configuration.get(Configuration.PROPERTY_AZURE_IDENTITY_DISABLE_CP1, false); multiTenantAuthDisabled = configuration .get(AZURE_IDENTITY_DISABLE_MULTI_TENANT_AUTH, false); } /** * Gets the timeout to apply to developer credential operations. * @return The timeout value for developer credential operations. */ public Duration getCredentialProcessTimeout() { return credentialProcessTimeout; } /** * Sets the timeout for developer credential operations. * @param credentialProcessTimeout The timeout value for developer credential operations. */ public void setCredentialProcessTimeout(Duration credentialProcessTimeout) { this.credentialProcessTimeout = credentialProcessTimeout; } /** * Indicates whether this options instance is part of a {@link ChainedTokenCredential}. * @return true if this options instance is part of a {@link ChainedTokenCredential}, false otherwise. */ public boolean isChained() { return this.isChained; } /** * Sets whether this options instance is part of a {@link ChainedTokenCredential}. * @param isChained * @return the updated client options */ public IdentityClientOptions setChained(boolean isChained) { this.isChained = isChained; return this; } }
class IdentityClientOptions implements Cloneable { private static final ClientLogger LOGGER = new ClientLogger(IdentityClientOptions.class); private static final int MAX_RETRY_DEFAULT_LIMIT = 3; public static final String AZURE_IDENTITY_DISABLE_MULTI_TENANT_AUTH = "AZURE_IDENTITY_DISABLE_MULTITENANTAUTH"; public static final String AZURE_POD_IDENTITY_AUTHORITY_HOST = "AZURE_POD_IDENTITY_AUTHORITY_HOST"; private String authorityHost; private String imdsAuthorityHost; private int maxRetry; private Function<Duration, Duration> retryTimeout; private ProxyOptions proxyOptions; private HttpPipeline httpPipeline; private ExecutorService executorService; private HttpClient httpClient; private boolean allowUnencryptedCache; private boolean sharedTokenCacheEnabled; private String keePassDatabasePath; private boolean includeX5c; private AuthenticationRecord authenticationRecord; private TokenCachePersistenceOptions tokenCachePersistenceOptions; private boolean cp1Disabled; private RegionalAuthority regionalAuthority; private UserAssertion userAssertion; private boolean multiTenantAuthDisabled; private Configuration configuration; private IdentityLogOptionsImpl identityLogOptionsImpl; private boolean accountIdentifierLogging; private ManagedIdentityType managedIdentityType; private ManagedIdentityParameters managedIdentityParameters; private Set<String> additionallyAllowedTenants; private ClientOptions clientOptions; private HttpLogOptions httpLogOptions; private RetryOptions retryOptions; private RetryPolicy retryPolicy; private List<HttpPipelinePolicy> perCallPolicies; private List<HttpPipelinePolicy> perRetryPolicies; private boolean instanceDiscovery; private Duration credentialProcessTimeout = Duration.ofSeconds(10); private boolean isChained; /** * Creates an instance of IdentityClientOptions with default settings. */ public IdentityClientOptions() { Configuration configuration = Configuration.getGlobalConfiguration().clone(); loadFromConfiguration(configuration); identityLogOptionsImpl = new IdentityLogOptionsImpl(); maxRetry = MAX_RETRY_DEFAULT_LIMIT; retryTimeout = i -> Duration.ofSeconds((long) Math.pow(2, i.getSeconds() - 1)); perCallPolicies = new ArrayList<>(); perRetryPolicies = new ArrayList<>(); additionallyAllowedTenants = new HashSet<>(); regionalAuthority = RegionalAuthority.fromString( configuration.get(Configuration.PROPERTY_AZURE_REGIONAL_AUTHORITY_NAME)); instanceDiscovery = true; } /** * @return the Azure Active Directory endpoint to acquire tokens. */ public String getAuthorityHost() { return authorityHost; } /** * Specifies the Azure Active Directory endpoint to acquire tokens. * @param authorityHost the Azure Active Directory endpoint * @return IdentityClientOptions */ public IdentityClientOptions setAuthorityHost(String authorityHost) { this.authorityHost = authorityHost; return this; } /** * @return the AKS Pod Authority endpoint to acquire tokens. */ public String getImdsAuthorityHost() { return imdsAuthorityHost; } /** * @return the max number of retries when an authentication request fails. */ public int getMaxRetry() { return maxRetry; } /** * Specifies the max number of retries when an authentication request fails. * @param maxRetry the number of retries * @return IdentityClientOptions */ public IdentityClientOptions setMaxRetry(int maxRetry) { this.maxRetry = maxRetry; return this; } /** * @return a Function to calculate seconds of timeout on every retried request. */ public Function<Duration, Duration> getRetryTimeout() { return retryTimeout; } /** * Specifies a Function to calculate seconds of timeout on every retried request. * @param retryTimeout the Function that returns a timeout in seconds given the number of retry * @return IdentityClientOptions */ public IdentityClientOptions setRetryTimeout(Function<Duration, Duration> retryTimeout) { this.retryTimeout = retryTimeout; return this; } /** * @return the options for proxy configuration. */ public ProxyOptions getProxyOptions() { return proxyOptions; } /** * Specifies the options for proxy configuration. * @param proxyOptions the options for proxy configuration * @return IdentityClientOptions */ public IdentityClientOptions setProxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * @return the HttpPipeline to send all requests */ public HttpPipeline getHttpPipeline() { return httpPipeline; } /** * @return the HttpClient to use for requests */ public HttpClient getHttpClient() { return httpClient; } /** * Specifies the HttpPipeline to send all requests. This setting overrides the others. * @param httpPipeline the HttpPipeline to send all requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpPipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Specifies the ExecutorService to be used to execute the authentication requests. * Developer is responsible for maintaining the lifecycle of the ExecutorService. * * <p> * If this is not configured, the {@link ForkJoinPool * also shared with other application tasks. If the common pool is heavily used for other tasks, authentication * requests might starve and setting up this executor service should be considered. * </p> * * <p> The executor service and can be safely shutdown if the TokenCredential is no longer being used by the * Azure SDK clients and should be shutdown before the application exits. </p> * * @param executorService the executor service to use for executing authentication requests. * @return IdentityClientOptions */ public IdentityClientOptions setExecutorService(ExecutorService executorService) { this.executorService = executorService; return this; } /** * @return the ExecutorService to execute authentication requests. */ public ExecutorService getExecutorService() { return executorService; } /** * Specifies the HttpClient to send use for requests. * @param httpClient the http client to use for requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @param allowUnencryptedCache the flag to indicate if unencrypted persistent cache is allowed for use or not. * @return The updated identity client options. */ public IdentityClientOptions setAllowUnencryptedCache(boolean allowUnencryptedCache) { this.allowUnencryptedCache = allowUnencryptedCache; return this; } public boolean getAllowUnencryptedCache() { return this.allowUnencryptedCache; } /** * Specifies the database to extract IntelliJ cached credentials from. * @param keePassDatabasePath the database to extract intellij credentials from. * @return IdentityClientOptions */ public IdentityClientOptions setIntelliJKeePassDatabasePath(String keePassDatabasePath) { this.keePassDatabasePath = keePassDatabasePath; return this; } /** * Gets if the shared token cache is disabled. * @return if the shared token cache is disabled. */ public boolean isSharedTokenCacheEnabled() { return this.sharedTokenCacheEnabled; } /** * Enables the shared token cache which is disabled by default. If enabled, the client will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return The updated identity client options. */ public IdentityClientOptions enablePersistentCache() { this.sharedTokenCacheEnabled = true; return this; } /* * Get the KeePass database path. * @return the KeePass database path to extract inellij credentials from. */ public String getIntelliJKeePassDatabasePath() { return keePassDatabasePath; } /** * Sets the {@link AuthenticationRecord} captured from a previous authentication. * * @param authenticationRecord The Authentication record to be configured. * * @return An updated instance of this builder with the configured authentication record. */ public IdentityClientOptions setAuthenticationRecord(AuthenticationRecord authenticationRecord) { this.authenticationRecord = authenticationRecord; return this; } /** * Get the status whether x5c claim (public key of the certificate) should be included as part of the authentication * request or not. * @return the status of x5c claim inclusion. */ public boolean isIncludeX5c() { return includeX5c; } /** * Specifies if the x5c claim (public key of the certificate) should be sent as part of the authentication request. * The default value is false. * * @param includeX5c true if the x5c should be sent. Otherwise false * @return The updated identity client options. */ public IdentityClientOptions setIncludeX5c(boolean includeX5c) { this.includeX5c = includeX5c; return this; } /** * Get the configured {@link AuthenticationRecord}. * * @return {@link AuthenticationRecord}. */ public AuthenticationRecord getAuthenticationRecord() { return authenticationRecord; } /** * Specifies the {@link TokenCachePersistenceOptions} to be used for token cache persistence. * * @param tokenCachePersistenceOptions the options configuration * @return the updated identity client options */ public IdentityClientOptions setTokenCacheOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { this.tokenCachePersistenceOptions = tokenCachePersistenceOptions; return this; } /** * Get the configured {@link TokenCachePersistenceOptions} * * @return the {@link TokenCachePersistenceOptions} */ public TokenCachePersistenceOptions getTokenCacheOptions() { return this.tokenCachePersistenceOptions; } /** * Check whether CP1 client capability should be disabled. * * @return the status indicating if CP1 client capability should be disabled. */ public boolean isCp1Disabled() { return this.cp1Disabled; } /** * Gets the regional authority, or null if regional authority should not be used. * @return the regional authority value if specified */ public RegionalAuthority getRegionalAuthority() { return regionalAuthority; } /** * Configure the User Assertion Scope to be used for OnBehalfOf Authentication request. * * @param userAssertion the user assertion access token to be used for On behalf Of authentication flow * @return the updated identity client options */ public IdentityClientOptions userAssertion(String userAssertion) { this.userAssertion = new UserAssertion(userAssertion); return this; } /** * Get the configured {@link UserAssertion} * * @return the configured user assertion scope */ public UserAssertion getUserAssertion() { return this.userAssertion; } /** * Gets the status whether multi tenant auth is disabled or not. * @return the flag indicating if multi tenant is disabled or not. */ public boolean isMultiTenantAuthenticationDisabled() { return multiTenantAuthDisabled; } /** * Disable the multi tenant authentication. * @return the updated identity client options */ public IdentityClientOptions disableMultiTenantAuthentication() { this.multiTenantAuthDisabled = true; return this; } /** * Sets the specified configuration store. * * @param configuration the configuration store to be used to read env variables and/or system properties. * @return the updated identity client options */ public IdentityClientOptions setConfiguration(Configuration configuration) { this.configuration = configuration; loadFromConfiguration(configuration); return this; } /** * Gets the configured configuration store. * * @return the configured {@link Configuration} store. */ public Configuration getConfiguration() { return this.configuration; } /** * Get the configured Identity Log options. * @return the identity log options. */ public IdentityLogOptionsImpl getIdentityLogOptionsImpl() { return identityLogOptionsImpl; } /** * Set the Identity Log options. * @return the identity log options. */ public IdentityClientOptions setIdentityLogOptionsImpl(IdentityLogOptionsImpl identityLogOptionsImpl) { this.identityLogOptionsImpl = identityLogOptionsImpl; return this; } /** * Set the Managed Identity Type * @param managedIdentityType the Managed Identity Type * @return the updated identity client options */ public IdentityClientOptions setManagedIdentityType(ManagedIdentityType managedIdentityType) { this.managedIdentityType = managedIdentityType; return this; } /** * Get the Managed Identity Type * @return the Managed Identity Type */ public ManagedIdentityType getManagedIdentityType() { return managedIdentityType; } /** * Get the Managed Identity parameters * @return the Managed Identity Parameters */ public ManagedIdentityParameters getManagedIdentityParameters() { return managedIdentityParameters; } /** * Configure the managed identity parameters. * * @param managedIdentityParameters the managed identity parameters to use for authentication. * @return the updated identity client options */ public IdentityClientOptions setManagedIdentityParameters(ManagedIdentityParameters managedIdentityParameters) { this.managedIdentityParameters = managedIdentityParameters; return this; } /** * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the application is installed. * * @param additionallyAllowedTenants the additionally allowed Tenants. * @return An updated instance of this builder with the tenant id set as specified. */ @SuppressWarnings("unchecked") public IdentityClientOptions setAdditionallyAllowedTenants(List<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); this.additionallyAllowedTenants.addAll(additionallyAllowedTenants); return this; } /** * Get the Additionally Allowed Tenants. * @return the List containing additionally allowed tenants. */ public Set<String> getAdditionallyAllowedTenants() { return this.additionallyAllowedTenants; } /** * Configure the client options. * @param clientOptions the client options input. * @return the updated client options */ public IdentityClientOptions setClientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Get the configured client options. * @return the client options. */ public ClientOptions getClientOptions() { return this.clientOptions; } /** * Configure the client options. * @param httpLogOptions the Http log options input. * @return the updated client options */ public IdentityClientOptions setHttpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /** * Get the configured Http log options. * @return the Http log options. */ public HttpLogOptions getHttpLogOptions() { return this.httpLogOptions; } /** * Configure the retry options. * @param retryOptions the retry options input. * @return the updated client options */ public IdentityClientOptions setRetryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Get the configured retry options. * @return the retry options. */ public RetryOptions getRetryOptions() { return this.retryOptions; } /** * Configure the retry policy. * @param retryPolicy the retry policy. * @return the updated client options */ public IdentityClientOptions setRetryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Get the configured retry policy. * @return the retry policy. */ public RetryPolicy getRetryPolicy() { return this.retryPolicy; } /** * Add a per call policy. * @param httpPipelinePolicy the http pipeline policy to add. * @return the updated client options */ public IdentityClientOptions addPerCallPolicy(HttpPipelinePolicy httpPipelinePolicy) { this.perCallPolicies.add(httpPipelinePolicy); return this; } /** * Add a per retry policy. * @param httpPipelinePolicy the retry policy to be added. * @return the updated client options */ public IdentityClientOptions addPerRetryPolicy(HttpPipelinePolicy httpPipelinePolicy) { this.perRetryPolicies.add(httpPipelinePolicy); return this; } /** * Get the configured per retry policies. * @return the per retry policies. */ public List<HttpPipelinePolicy> getPerRetryPolicies() { return this.perRetryPolicies; } /** * Get the configured per call policies. * @return the per call policies. */ public List<HttpPipelinePolicy> getPerCallPolicies() { return this.perCallPolicies; } IdentityClientOptions setCp1Disabled(boolean cp1Disabled) { this.cp1Disabled = cp1Disabled; return this; } IdentityClientOptions setMultiTenantAuthDisabled(boolean multiTenantAuthDisabled) { this.multiTenantAuthDisabled = multiTenantAuthDisabled; return this; } IdentityClientOptions setAdditionallyAllowedTenants(Set<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = additionallyAllowedTenants; return this; } /** * Specifies either the specific regional authority, or use {@link RegionalAuthority * * @param regionalAuthority the regional authority * @return the updated identity client options */ IdentityClientOptions setRegionalAuthority(RegionalAuthority regionalAuthority) { this.regionalAuthority = regionalAuthority; return this; } IdentityClientOptions setConfigurationStore(Configuration configuration) { this.configuration = configuration; return this; } IdentityClientOptions setUserAssertion(UserAssertion userAssertion) { this.userAssertion = userAssertion; return this; } IdentityClientOptions setPersistenceCache(boolean persistenceCache) { this.sharedTokenCacheEnabled = persistenceCache; return this; } IdentityClientOptions setImdsAuthorityHost(String imdsAuthorityHost) { this.imdsAuthorityHost = imdsAuthorityHost; return this; } IdentityClientOptions setPerCallPolicies(List<HttpPipelinePolicy> perCallPolicies) { this.perCallPolicies = perCallPolicies; return this; } IdentityClientOptions setPerRetryPolicies(List<HttpPipelinePolicy> perRetryPolicies) { this.perRetryPolicies = perRetryPolicies; return this; } /** * Disables authority validation and instance discovery. * Instance discovery is acquiring metadata about an authority from https: * to validate that authority. This may need to be disabled in private cloud or ADFS scenarios. * * @return the updated client options */ public IdentityClientOptions disableInstanceDiscovery() { this.instanceDiscovery = false; return this; } /** * Gets the instance discovery policy. * @return boolean indicating if instance discovery is enabled. */ public boolean isInstanceDiscoveryEnabled() { return this.instanceDiscovery; } /** * Loads the details from the specified Configuration Store. */ private void loadFromConfiguration(Configuration configuration) { authorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); imdsAuthorityHost = configuration.get(AZURE_POD_IDENTITY_AUTHORITY_HOST, IdentityConstants.DEFAULT_IMDS_ENDPOINT); ValidationUtil.validateAuthHost(authorityHost, LOGGER); cp1Disabled = configuration.get(Configuration.PROPERTY_AZURE_IDENTITY_DISABLE_CP1, false); multiTenantAuthDisabled = configuration .get(AZURE_IDENTITY_DISABLE_MULTI_TENANT_AUTH, false); } /** * Gets the timeout to apply to developer credential operations. * @return The timeout value for developer credential operations. */ public Duration getCredentialProcessTimeout() { return credentialProcessTimeout; } /** * Sets the timeout for developer credential operations. * @param credentialProcessTimeout The timeout value for developer credential operations. */ public void setCredentialProcessTimeout(Duration credentialProcessTimeout) { this.credentialProcessTimeout = credentialProcessTimeout; } /** * Indicates whether this options instance is part of a {@link ChainedTokenCredential}. * @return true if this options instance is part of a {@link ChainedTokenCredential}, false otherwise. */ public boolean isChained() { return this.isChained; } /** * Sets whether this options instance is part of a {@link ChainedTokenCredential}. * @param isChained * @return the updated client options */ public IdentityClientOptions setChained(boolean isChained) { this.isChained = isChained; return this; } }
fixed
public IdentityClientOptions clone() { IdentityClientOptions clone = new IdentityClientOptions() .setAdditionallyAllowedTenants(this.additionallyAllowedTenants) .setAllowUnencryptedCache(this.allowUnencryptedCache) .setHttpClient(this.httpClient) .setAuthenticationRecord(this.authenticationRecord) .setExecutorService(this.executorService) .setIdentityLogOptionsImpl(this.identityLogOptionsImpl) .setTokenCacheOptions(this.tokenCachePersistenceOptions) .setRetryTimeout(this.retryTimeout) .setRegionalAuthority(this.regionalAuthority) .setHttpPipeline(this.httpPipeline) .setIncludeX5c(this.includeX5c) .setProxyOptions(this.proxyOptions) .setMaxRetry(this.maxRetry) .setIntelliJKeePassDatabasePath(this.keePassDatabasePath) .setAuthorityHost(this.authorityHost) .setImdsAuthorityHost(this.imdsAuthorityHost) .setCp1Disabled(this.cp1Disabled) .setMultiTenantAuthDisabled(this.multiTenantAuthDisabled) .setUserAssertion(this.userAssertion) .setConfigurationStore(this.configuration) .setPersistenceCache(this.sharedTokenCacheEnabled) .setClientOptions(this.clientOptions) .setHttpLogOptions(this.httpLogOptions) .setRetryOptions(this.retryOptions) .setRetryPolicy(this.retryPolicy) .setPerCallPolicies(this.perCallPolicies) .setPerRetryPolicies(this.perRetryPolicies); if (!isInstanceDiscoveryEnabled()) { clone.disableInstanceDiscovery(); } return clone; }
IdentityClientOptions clone = new IdentityClientOptions()
public IdentityClientOptions clone() { IdentityClientOptions clone = new IdentityClientOptions() .setAdditionallyAllowedTenants(this.additionallyAllowedTenants) .setAllowUnencryptedCache(this.allowUnencryptedCache) .setHttpClient(this.httpClient) .setAuthenticationRecord(this.authenticationRecord) .setExecutorService(this.executorService) .setIdentityLogOptionsImpl(this.identityLogOptionsImpl) .setTokenCacheOptions(this.tokenCachePersistenceOptions) .setRetryTimeout(this.retryTimeout) .setRegionalAuthority(this.regionalAuthority) .setHttpPipeline(this.httpPipeline) .setIncludeX5c(this.includeX5c) .setProxyOptions(this.proxyOptions) .setMaxRetry(this.maxRetry) .setIntelliJKeePassDatabasePath(this.keePassDatabasePath) .setAuthorityHost(this.authorityHost) .setImdsAuthorityHost(this.imdsAuthorityHost) .setCp1Disabled(this.cp1Disabled) .setMultiTenantAuthDisabled(this.multiTenantAuthDisabled) .setUserAssertion(this.userAssertion) .setConfigurationStore(this.configuration) .setPersistenceCache(this.sharedTokenCacheEnabled) .setClientOptions(this.clientOptions) .setHttpLogOptions(this.httpLogOptions) .setRetryOptions(this.retryOptions) .setRetryPolicy(this.retryPolicy) .setPerCallPolicies(this.perCallPolicies) .setPerRetryPolicies(this.perRetryPolicies) .setChained(this.isChained); if (!isInstanceDiscoveryEnabled()) { clone.disableInstanceDiscovery(); } return clone; }
class IdentityClientOptions implements Cloneable { private static final ClientLogger LOGGER = new ClientLogger(IdentityClientOptions.class); private static final int MAX_RETRY_DEFAULT_LIMIT = 3; public static final String AZURE_IDENTITY_DISABLE_MULTI_TENANT_AUTH = "AZURE_IDENTITY_DISABLE_MULTITENANTAUTH"; public static final String AZURE_POD_IDENTITY_AUTHORITY_HOST = "AZURE_POD_IDENTITY_AUTHORITY_HOST"; private String authorityHost; private String imdsAuthorityHost; private int maxRetry; private Function<Duration, Duration> retryTimeout; private ProxyOptions proxyOptions; private HttpPipeline httpPipeline; private ExecutorService executorService; private HttpClient httpClient; private boolean allowUnencryptedCache; private boolean sharedTokenCacheEnabled; private String keePassDatabasePath; private boolean includeX5c; private AuthenticationRecord authenticationRecord; private TokenCachePersistenceOptions tokenCachePersistenceOptions; private boolean cp1Disabled; private RegionalAuthority regionalAuthority; private UserAssertion userAssertion; private boolean multiTenantAuthDisabled; private Configuration configuration; private IdentityLogOptionsImpl identityLogOptionsImpl; private boolean accountIdentifierLogging; private ManagedIdentityType managedIdentityType; private ManagedIdentityParameters managedIdentityParameters; private Set<String> additionallyAllowedTenants; private ClientOptions clientOptions; private HttpLogOptions httpLogOptions; private RetryOptions retryOptions; private RetryPolicy retryPolicy; private List<HttpPipelinePolicy> perCallPolicies; private List<HttpPipelinePolicy> perRetryPolicies; private boolean instanceDiscovery; private Duration credentialProcessTimeout = Duration.ofSeconds(10); private boolean isChained; /** * Creates an instance of IdentityClientOptions with default settings. */ public IdentityClientOptions() { Configuration configuration = Configuration.getGlobalConfiguration().clone(); loadFromConfiguration(configuration); identityLogOptionsImpl = new IdentityLogOptionsImpl(); maxRetry = MAX_RETRY_DEFAULT_LIMIT; retryTimeout = i -> Duration.ofSeconds((long) Math.pow(2, i.getSeconds() - 1)); perCallPolicies = new ArrayList<>(); perRetryPolicies = new ArrayList<>(); additionallyAllowedTenants = new HashSet<>(); regionalAuthority = RegionalAuthority.fromString( configuration.get(Configuration.PROPERTY_AZURE_REGIONAL_AUTHORITY_NAME)); instanceDiscovery = true; } /** * @return the Azure Active Directory endpoint to acquire tokens. */ public String getAuthorityHost() { return authorityHost; } /** * Specifies the Azure Active Directory endpoint to acquire tokens. * @param authorityHost the Azure Active Directory endpoint * @return IdentityClientOptions */ public IdentityClientOptions setAuthorityHost(String authorityHost) { this.authorityHost = authorityHost; return this; } /** * @return the AKS Pod Authority endpoint to acquire tokens. */ public String getImdsAuthorityHost() { return imdsAuthorityHost; } /** * @return the max number of retries when an authentication request fails. */ public int getMaxRetry() { return maxRetry; } /** * Specifies the max number of retries when an authentication request fails. * @param maxRetry the number of retries * @return IdentityClientOptions */ public IdentityClientOptions setMaxRetry(int maxRetry) { this.maxRetry = maxRetry; return this; } /** * @return a Function to calculate seconds of timeout on every retried request. */ public Function<Duration, Duration> getRetryTimeout() { return retryTimeout; } /** * Specifies a Function to calculate seconds of timeout on every retried request. * @param retryTimeout the Function that returns a timeout in seconds given the number of retry * @return IdentityClientOptions */ public IdentityClientOptions setRetryTimeout(Function<Duration, Duration> retryTimeout) { this.retryTimeout = retryTimeout; return this; } /** * @return the options for proxy configuration. */ public ProxyOptions getProxyOptions() { return proxyOptions; } /** * Specifies the options for proxy configuration. * @param proxyOptions the options for proxy configuration * @return IdentityClientOptions */ public IdentityClientOptions setProxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * @return the HttpPipeline to send all requests */ public HttpPipeline getHttpPipeline() { return httpPipeline; } /** * @return the HttpClient to use for requests */ public HttpClient getHttpClient() { return httpClient; } /** * Specifies the HttpPipeline to send all requests. This setting overrides the others. * @param httpPipeline the HttpPipeline to send all requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpPipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Specifies the ExecutorService to be used to execute the authentication requests. * Developer is responsible for maintaining the lifecycle of the ExecutorService. * * <p> * If this is not configured, the {@link ForkJoinPool * also shared with other application tasks. If the common pool is heavily used for other tasks, authentication * requests might starve and setting up this executor service should be considered. * </p> * * <p> The executor service and can be safely shutdown if the TokenCredential is no longer being used by the * Azure SDK clients and should be shutdown before the application exits. </p> * * @param executorService the executor service to use for executing authentication requests. * @return IdentityClientOptions */ public IdentityClientOptions setExecutorService(ExecutorService executorService) { this.executorService = executorService; return this; } /** * @return the ExecutorService to execute authentication requests. */ public ExecutorService getExecutorService() { return executorService; } /** * Specifies the HttpClient to send use for requests. * @param httpClient the http client to use for requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @param allowUnencryptedCache the flag to indicate if unencrypted persistent cache is allowed for use or not. * @return The updated identity client options. */ public IdentityClientOptions setAllowUnencryptedCache(boolean allowUnencryptedCache) { this.allowUnencryptedCache = allowUnencryptedCache; return this; } public boolean getAllowUnencryptedCache() { return this.allowUnencryptedCache; } /** * Specifies the database to extract IntelliJ cached credentials from. * @param keePassDatabasePath the database to extract intellij credentials from. * @return IdentityClientOptions */ public IdentityClientOptions setIntelliJKeePassDatabasePath(String keePassDatabasePath) { this.keePassDatabasePath = keePassDatabasePath; return this; } /** * Gets if the shared token cache is disabled. * @return if the shared token cache is disabled. */ public boolean isSharedTokenCacheEnabled() { return this.sharedTokenCacheEnabled; } /** * Enables the shared token cache which is disabled by default. If enabled, the client will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return The updated identity client options. */ public IdentityClientOptions enablePersistentCache() { this.sharedTokenCacheEnabled = true; return this; } /* * Get the KeePass database path. * @return the KeePass database path to extract inellij credentials from. */ public String getIntelliJKeePassDatabasePath() { return keePassDatabasePath; } /** * Sets the {@link AuthenticationRecord} captured from a previous authentication. * * @param authenticationRecord The Authentication record to be configured. * * @return An updated instance of this builder with the configured authentication record. */ public IdentityClientOptions setAuthenticationRecord(AuthenticationRecord authenticationRecord) { this.authenticationRecord = authenticationRecord; return this; } /** * Get the status whether x5c claim (public key of the certificate) should be included as part of the authentication * request or not. * @return the status of x5c claim inclusion. */ public boolean isIncludeX5c() { return includeX5c; } /** * Specifies if the x5c claim (public key of the certificate) should be sent as part of the authentication request. * The default value is false. * * @param includeX5c true if the x5c should be sent. Otherwise false * @return The updated identity client options. */ public IdentityClientOptions setIncludeX5c(boolean includeX5c) { this.includeX5c = includeX5c; return this; } /** * Get the configured {@link AuthenticationRecord}. * * @return {@link AuthenticationRecord}. */ public AuthenticationRecord getAuthenticationRecord() { return authenticationRecord; } /** * Specifies the {@link TokenCachePersistenceOptions} to be used for token cache persistence. * * @param tokenCachePersistenceOptions the options configuration * @return the updated identity client options */ public IdentityClientOptions setTokenCacheOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { this.tokenCachePersistenceOptions = tokenCachePersistenceOptions; return this; } /** * Get the configured {@link TokenCachePersistenceOptions} * * @return the {@link TokenCachePersistenceOptions} */ public TokenCachePersistenceOptions getTokenCacheOptions() { return this.tokenCachePersistenceOptions; } /** * Check whether CP1 client capability should be disabled. * * @return the status indicating if CP1 client capability should be disabled. */ public boolean isCp1Disabled() { return this.cp1Disabled; } /** * Gets the regional authority, or null if regional authority should not be used. * @return the regional authority value if specified */ public RegionalAuthority getRegionalAuthority() { return regionalAuthority; } /** * Configure the User Assertion Scope to be used for OnBehalfOf Authentication request. * * @param userAssertion the user assertion access token to be used for On behalf Of authentication flow * @return the updated identity client options */ public IdentityClientOptions userAssertion(String userAssertion) { this.userAssertion = new UserAssertion(userAssertion); return this; } /** * Get the configured {@link UserAssertion} * * @return the configured user assertion scope */ public UserAssertion getUserAssertion() { return this.userAssertion; } /** * Gets the status whether multi tenant auth is disabled or not. * @return the flag indicating if multi tenant is disabled or not. */ public boolean isMultiTenantAuthenticationDisabled() { return multiTenantAuthDisabled; } /** * Disable the multi tenant authentication. * @return the updated identity client options */ public IdentityClientOptions disableMultiTenantAuthentication() { this.multiTenantAuthDisabled = true; return this; } /** * Sets the specified configuration store. * * @param configuration the configuration store to be used to read env variables and/or system properties. * @return the updated identity client options */ public IdentityClientOptions setConfiguration(Configuration configuration) { this.configuration = configuration; loadFromConfiguration(configuration); return this; } /** * Gets the configured configuration store. * * @return the configured {@link Configuration} store. */ public Configuration getConfiguration() { return this.configuration; } /** * Get the configured Identity Log options. * @return the identity log options. */ public IdentityLogOptionsImpl getIdentityLogOptionsImpl() { return identityLogOptionsImpl; } /** * Set the Identity Log options. * @return the identity log options. */ public IdentityClientOptions setIdentityLogOptionsImpl(IdentityLogOptionsImpl identityLogOptionsImpl) { this.identityLogOptionsImpl = identityLogOptionsImpl; return this; } /** * Set the Managed Identity Type * @param managedIdentityType the Managed Identity Type * @return the updated identity client options */ public IdentityClientOptions setManagedIdentityType(ManagedIdentityType managedIdentityType) { this.managedIdentityType = managedIdentityType; return this; } /** * Get the Managed Identity Type * @return the Managed Identity Type */ public ManagedIdentityType getManagedIdentityType() { return managedIdentityType; } /** * Get the Managed Identity parameters * @return the Managed Identity Parameters */ public ManagedIdentityParameters getManagedIdentityParameters() { return managedIdentityParameters; } /** * Configure the managed identity parameters. * * @param managedIdentityParameters the managed identity parameters to use for authentication. * @return the updated identity client options */ public IdentityClientOptions setManagedIdentityParameters(ManagedIdentityParameters managedIdentityParameters) { this.managedIdentityParameters = managedIdentityParameters; return this; } /** * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the application is installed. * * @param additionallyAllowedTenants the additionally allowed Tenants. * @return An updated instance of this builder with the tenant id set as specified. */ @SuppressWarnings("unchecked") public IdentityClientOptions setAdditionallyAllowedTenants(List<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); this.additionallyAllowedTenants.addAll(additionallyAllowedTenants); return this; } /** * Get the Additionally Allowed Tenants. * @return the List containing additionally allowed tenants. */ public Set<String> getAdditionallyAllowedTenants() { return this.additionallyAllowedTenants; } /** * Configure the client options. * @param clientOptions the client options input. * @return the updated client options */ public IdentityClientOptions setClientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Get the configured client options. * @return the client options. */ public ClientOptions getClientOptions() { return this.clientOptions; } /** * Configure the client options. * @param httpLogOptions the Http log options input. * @return the updated client options */ public IdentityClientOptions setHttpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /** * Get the configured Http log options. * @return the Http log options. */ public HttpLogOptions getHttpLogOptions() { return this.httpLogOptions; } /** * Configure the retry options. * @param retryOptions the retry options input. * @return the updated client options */ public IdentityClientOptions setRetryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Get the configured retry options. * @return the retry options. */ public RetryOptions getRetryOptions() { return this.retryOptions; } /** * Configure the retry policy. * @param retryPolicy the retry policy. * @return the updated client options */ public IdentityClientOptions setRetryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Get the configured retry policy. * @return the retry policy. */ public RetryPolicy getRetryPolicy() { return this.retryPolicy; } /** * Add a per call policy. * @param httpPipelinePolicy the http pipeline policy to add. * @return the updated client options */ public IdentityClientOptions addPerCallPolicy(HttpPipelinePolicy httpPipelinePolicy) { this.perCallPolicies.add(httpPipelinePolicy); return this; } /** * Add a per retry policy. * @param httpPipelinePolicy the retry policy to be added. * @return the updated client options */ public IdentityClientOptions addPerRetryPolicy(HttpPipelinePolicy httpPipelinePolicy) { this.perRetryPolicies.add(httpPipelinePolicy); return this; } /** * Get the configured per retry policies. * @return the per retry policies. */ public List<HttpPipelinePolicy> getPerRetryPolicies() { return this.perRetryPolicies; } /** * Get the configured per call policies. * @return the per call policies. */ public List<HttpPipelinePolicy> getPerCallPolicies() { return this.perCallPolicies; } IdentityClientOptions setCp1Disabled(boolean cp1Disabled) { this.cp1Disabled = cp1Disabled; return this; } IdentityClientOptions setMultiTenantAuthDisabled(boolean multiTenantAuthDisabled) { this.multiTenantAuthDisabled = multiTenantAuthDisabled; return this; } IdentityClientOptions setAdditionallyAllowedTenants(Set<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = additionallyAllowedTenants; return this; } /** * Specifies either the specific regional authority, or use {@link RegionalAuthority * * @param regionalAuthority the regional authority * @return the updated identity client options */ IdentityClientOptions setRegionalAuthority(RegionalAuthority regionalAuthority) { this.regionalAuthority = regionalAuthority; return this; } IdentityClientOptions setConfigurationStore(Configuration configuration) { this.configuration = configuration; return this; } IdentityClientOptions setUserAssertion(UserAssertion userAssertion) { this.userAssertion = userAssertion; return this; } IdentityClientOptions setPersistenceCache(boolean persistenceCache) { this.sharedTokenCacheEnabled = persistenceCache; return this; } IdentityClientOptions setImdsAuthorityHost(String imdsAuthorityHost) { this.imdsAuthorityHost = imdsAuthorityHost; return this; } IdentityClientOptions setPerCallPolicies(List<HttpPipelinePolicy> perCallPolicies) { this.perCallPolicies = perCallPolicies; return this; } IdentityClientOptions setPerRetryPolicies(List<HttpPipelinePolicy> perRetryPolicies) { this.perRetryPolicies = perRetryPolicies; return this; } /** * Disables authority validation and instance discovery. * Instance discovery is acquiring metadata about an authority from https: * to validate that authority. This may need to be disabled in private cloud or ADFS scenarios. * * @return the updated client options */ public IdentityClientOptions disableInstanceDiscovery() { this.instanceDiscovery = false; return this; } /** * Gets the instance discovery policy. * @return boolean indicating if instance discovery is enabled. */ public boolean isInstanceDiscoveryEnabled() { return this.instanceDiscovery; } /** * Loads the details from the specified Configuration Store. */ private void loadFromConfiguration(Configuration configuration) { authorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); imdsAuthorityHost = configuration.get(AZURE_POD_IDENTITY_AUTHORITY_HOST, IdentityConstants.DEFAULT_IMDS_ENDPOINT); ValidationUtil.validateAuthHost(authorityHost, LOGGER); cp1Disabled = configuration.get(Configuration.PROPERTY_AZURE_IDENTITY_DISABLE_CP1, false); multiTenantAuthDisabled = configuration .get(AZURE_IDENTITY_DISABLE_MULTI_TENANT_AUTH, false); } /** * Gets the timeout to apply to developer credential operations. * @return The timeout value for developer credential operations. */ public Duration getCredentialProcessTimeout() { return credentialProcessTimeout; } /** * Sets the timeout for developer credential operations. * @param credentialProcessTimeout The timeout value for developer credential operations. */ public void setCredentialProcessTimeout(Duration credentialProcessTimeout) { this.credentialProcessTimeout = credentialProcessTimeout; } /** * Indicates whether this options instance is part of a {@link ChainedTokenCredential}. * @return true if this options instance is part of a {@link ChainedTokenCredential}, false otherwise. */ public boolean isChained() { return this.isChained; } /** * Sets whether this options instance is part of a {@link ChainedTokenCredential}. * @param isChained * @return the updated client options */ public IdentityClientOptions setChained(boolean isChained) { this.isChained = isChained; return this; } }
class IdentityClientOptions implements Cloneable { private static final ClientLogger LOGGER = new ClientLogger(IdentityClientOptions.class); private static final int MAX_RETRY_DEFAULT_LIMIT = 3; public static final String AZURE_IDENTITY_DISABLE_MULTI_TENANT_AUTH = "AZURE_IDENTITY_DISABLE_MULTITENANTAUTH"; public static final String AZURE_POD_IDENTITY_AUTHORITY_HOST = "AZURE_POD_IDENTITY_AUTHORITY_HOST"; private String authorityHost; private String imdsAuthorityHost; private int maxRetry; private Function<Duration, Duration> retryTimeout; private ProxyOptions proxyOptions; private HttpPipeline httpPipeline; private ExecutorService executorService; private HttpClient httpClient; private boolean allowUnencryptedCache; private boolean sharedTokenCacheEnabled; private String keePassDatabasePath; private boolean includeX5c; private AuthenticationRecord authenticationRecord; private TokenCachePersistenceOptions tokenCachePersistenceOptions; private boolean cp1Disabled; private RegionalAuthority regionalAuthority; private UserAssertion userAssertion; private boolean multiTenantAuthDisabled; private Configuration configuration; private IdentityLogOptionsImpl identityLogOptionsImpl; private boolean accountIdentifierLogging; private ManagedIdentityType managedIdentityType; private ManagedIdentityParameters managedIdentityParameters; private Set<String> additionallyAllowedTenants; private ClientOptions clientOptions; private HttpLogOptions httpLogOptions; private RetryOptions retryOptions; private RetryPolicy retryPolicy; private List<HttpPipelinePolicy> perCallPolicies; private List<HttpPipelinePolicy> perRetryPolicies; private boolean instanceDiscovery; private Duration credentialProcessTimeout = Duration.ofSeconds(10); private boolean isChained; /** * Creates an instance of IdentityClientOptions with default settings. */ public IdentityClientOptions() { Configuration configuration = Configuration.getGlobalConfiguration().clone(); loadFromConfiguration(configuration); identityLogOptionsImpl = new IdentityLogOptionsImpl(); maxRetry = MAX_RETRY_DEFAULT_LIMIT; retryTimeout = i -> Duration.ofSeconds((long) Math.pow(2, i.getSeconds() - 1)); perCallPolicies = new ArrayList<>(); perRetryPolicies = new ArrayList<>(); additionallyAllowedTenants = new HashSet<>(); regionalAuthority = RegionalAuthority.fromString( configuration.get(Configuration.PROPERTY_AZURE_REGIONAL_AUTHORITY_NAME)); instanceDiscovery = true; } /** * @return the Azure Active Directory endpoint to acquire tokens. */ public String getAuthorityHost() { return authorityHost; } /** * Specifies the Azure Active Directory endpoint to acquire tokens. * @param authorityHost the Azure Active Directory endpoint * @return IdentityClientOptions */ public IdentityClientOptions setAuthorityHost(String authorityHost) { this.authorityHost = authorityHost; return this; } /** * @return the AKS Pod Authority endpoint to acquire tokens. */ public String getImdsAuthorityHost() { return imdsAuthorityHost; } /** * @return the max number of retries when an authentication request fails. */ public int getMaxRetry() { return maxRetry; } /** * Specifies the max number of retries when an authentication request fails. * @param maxRetry the number of retries * @return IdentityClientOptions */ public IdentityClientOptions setMaxRetry(int maxRetry) { this.maxRetry = maxRetry; return this; } /** * @return a Function to calculate seconds of timeout on every retried request. */ public Function<Duration, Duration> getRetryTimeout() { return retryTimeout; } /** * Specifies a Function to calculate seconds of timeout on every retried request. * @param retryTimeout the Function that returns a timeout in seconds given the number of retry * @return IdentityClientOptions */ public IdentityClientOptions setRetryTimeout(Function<Duration, Duration> retryTimeout) { this.retryTimeout = retryTimeout; return this; } /** * @return the options for proxy configuration. */ public ProxyOptions getProxyOptions() { return proxyOptions; } /** * Specifies the options for proxy configuration. * @param proxyOptions the options for proxy configuration * @return IdentityClientOptions */ public IdentityClientOptions setProxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * @return the HttpPipeline to send all requests */ public HttpPipeline getHttpPipeline() { return httpPipeline; } /** * @return the HttpClient to use for requests */ public HttpClient getHttpClient() { return httpClient; } /** * Specifies the HttpPipeline to send all requests. This setting overrides the others. * @param httpPipeline the HttpPipeline to send all requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpPipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Specifies the ExecutorService to be used to execute the authentication requests. * Developer is responsible for maintaining the lifecycle of the ExecutorService. * * <p> * If this is not configured, the {@link ForkJoinPool * also shared with other application tasks. If the common pool is heavily used for other tasks, authentication * requests might starve and setting up this executor service should be considered. * </p> * * <p> The executor service and can be safely shutdown if the TokenCredential is no longer being used by the * Azure SDK clients and should be shutdown before the application exits. </p> * * @param executorService the executor service to use for executing authentication requests. * @return IdentityClientOptions */ public IdentityClientOptions setExecutorService(ExecutorService executorService) { this.executorService = executorService; return this; } /** * @return the ExecutorService to execute authentication requests. */ public ExecutorService getExecutorService() { return executorService; } /** * Specifies the HttpClient to send use for requests. * @param httpClient the http client to use for requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @param allowUnencryptedCache the flag to indicate if unencrypted persistent cache is allowed for use or not. * @return The updated identity client options. */ public IdentityClientOptions setAllowUnencryptedCache(boolean allowUnencryptedCache) { this.allowUnencryptedCache = allowUnencryptedCache; return this; } public boolean getAllowUnencryptedCache() { return this.allowUnencryptedCache; } /** * Specifies the database to extract IntelliJ cached credentials from. * @param keePassDatabasePath the database to extract intellij credentials from. * @return IdentityClientOptions */ public IdentityClientOptions setIntelliJKeePassDatabasePath(String keePassDatabasePath) { this.keePassDatabasePath = keePassDatabasePath; return this; } /** * Gets if the shared token cache is disabled. * @return if the shared token cache is disabled. */ public boolean isSharedTokenCacheEnabled() { return this.sharedTokenCacheEnabled; } /** * Enables the shared token cache which is disabled by default. If enabled, the client will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return The updated identity client options. */ public IdentityClientOptions enablePersistentCache() { this.sharedTokenCacheEnabled = true; return this; } /* * Get the KeePass database path. * @return the KeePass database path to extract inellij credentials from. */ public String getIntelliJKeePassDatabasePath() { return keePassDatabasePath; } /** * Sets the {@link AuthenticationRecord} captured from a previous authentication. * * @param authenticationRecord The Authentication record to be configured. * * @return An updated instance of this builder with the configured authentication record. */ public IdentityClientOptions setAuthenticationRecord(AuthenticationRecord authenticationRecord) { this.authenticationRecord = authenticationRecord; return this; } /** * Get the status whether x5c claim (public key of the certificate) should be included as part of the authentication * request or not. * @return the status of x5c claim inclusion. */ public boolean isIncludeX5c() { return includeX5c; } /** * Specifies if the x5c claim (public key of the certificate) should be sent as part of the authentication request. * The default value is false. * * @param includeX5c true if the x5c should be sent. Otherwise false * @return The updated identity client options. */ public IdentityClientOptions setIncludeX5c(boolean includeX5c) { this.includeX5c = includeX5c; return this; } /** * Get the configured {@link AuthenticationRecord}. * * @return {@link AuthenticationRecord}. */ public AuthenticationRecord getAuthenticationRecord() { return authenticationRecord; } /** * Specifies the {@link TokenCachePersistenceOptions} to be used for token cache persistence. * * @param tokenCachePersistenceOptions the options configuration * @return the updated identity client options */ public IdentityClientOptions setTokenCacheOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { this.tokenCachePersistenceOptions = tokenCachePersistenceOptions; return this; } /** * Get the configured {@link TokenCachePersistenceOptions} * * @return the {@link TokenCachePersistenceOptions} */ public TokenCachePersistenceOptions getTokenCacheOptions() { return this.tokenCachePersistenceOptions; } /** * Check whether CP1 client capability should be disabled. * * @return the status indicating if CP1 client capability should be disabled. */ public boolean isCp1Disabled() { return this.cp1Disabled; } /** * Gets the regional authority, or null if regional authority should not be used. * @return the regional authority value if specified */ public RegionalAuthority getRegionalAuthority() { return regionalAuthority; } /** * Configure the User Assertion Scope to be used for OnBehalfOf Authentication request. * * @param userAssertion the user assertion access token to be used for On behalf Of authentication flow * @return the updated identity client options */ public IdentityClientOptions userAssertion(String userAssertion) { this.userAssertion = new UserAssertion(userAssertion); return this; } /** * Get the configured {@link UserAssertion} * * @return the configured user assertion scope */ public UserAssertion getUserAssertion() { return this.userAssertion; } /** * Gets the status whether multi tenant auth is disabled or not. * @return the flag indicating if multi tenant is disabled or not. */ public boolean isMultiTenantAuthenticationDisabled() { return multiTenantAuthDisabled; } /** * Disable the multi tenant authentication. * @return the updated identity client options */ public IdentityClientOptions disableMultiTenantAuthentication() { this.multiTenantAuthDisabled = true; return this; } /** * Sets the specified configuration store. * * @param configuration the configuration store to be used to read env variables and/or system properties. * @return the updated identity client options */ public IdentityClientOptions setConfiguration(Configuration configuration) { this.configuration = configuration; loadFromConfiguration(configuration); return this; } /** * Gets the configured configuration store. * * @return the configured {@link Configuration} store. */ public Configuration getConfiguration() { return this.configuration; } /** * Get the configured Identity Log options. * @return the identity log options. */ public IdentityLogOptionsImpl getIdentityLogOptionsImpl() { return identityLogOptionsImpl; } /** * Set the Identity Log options. * @return the identity log options. */ public IdentityClientOptions setIdentityLogOptionsImpl(IdentityLogOptionsImpl identityLogOptionsImpl) { this.identityLogOptionsImpl = identityLogOptionsImpl; return this; } /** * Set the Managed Identity Type * @param managedIdentityType the Managed Identity Type * @return the updated identity client options */ public IdentityClientOptions setManagedIdentityType(ManagedIdentityType managedIdentityType) { this.managedIdentityType = managedIdentityType; return this; } /** * Get the Managed Identity Type * @return the Managed Identity Type */ public ManagedIdentityType getManagedIdentityType() { return managedIdentityType; } /** * Get the Managed Identity parameters * @return the Managed Identity Parameters */ public ManagedIdentityParameters getManagedIdentityParameters() { return managedIdentityParameters; } /** * Configure the managed identity parameters. * * @param managedIdentityParameters the managed identity parameters to use for authentication. * @return the updated identity client options */ public IdentityClientOptions setManagedIdentityParameters(ManagedIdentityParameters managedIdentityParameters) { this.managedIdentityParameters = managedIdentityParameters; return this; } /** * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the application is installed. * * @param additionallyAllowedTenants the additionally allowed Tenants. * @return An updated instance of this builder with the tenant id set as specified. */ @SuppressWarnings("unchecked") public IdentityClientOptions setAdditionallyAllowedTenants(List<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); this.additionallyAllowedTenants.addAll(additionallyAllowedTenants); return this; } /** * Get the Additionally Allowed Tenants. * @return the List containing additionally allowed tenants. */ public Set<String> getAdditionallyAllowedTenants() { return this.additionallyAllowedTenants; } /** * Configure the client options. * @param clientOptions the client options input. * @return the updated client options */ public IdentityClientOptions setClientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Get the configured client options. * @return the client options. */ public ClientOptions getClientOptions() { return this.clientOptions; } /** * Configure the client options. * @param httpLogOptions the Http log options input. * @return the updated client options */ public IdentityClientOptions setHttpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /** * Get the configured Http log options. * @return the Http log options. */ public HttpLogOptions getHttpLogOptions() { return this.httpLogOptions; } /** * Configure the retry options. * @param retryOptions the retry options input. * @return the updated client options */ public IdentityClientOptions setRetryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Get the configured retry options. * @return the retry options. */ public RetryOptions getRetryOptions() { return this.retryOptions; } /** * Configure the retry policy. * @param retryPolicy the retry policy. * @return the updated client options */ public IdentityClientOptions setRetryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Get the configured retry policy. * @return the retry policy. */ public RetryPolicy getRetryPolicy() { return this.retryPolicy; } /** * Add a per call policy. * @param httpPipelinePolicy the http pipeline policy to add. * @return the updated client options */ public IdentityClientOptions addPerCallPolicy(HttpPipelinePolicy httpPipelinePolicy) { this.perCallPolicies.add(httpPipelinePolicy); return this; } /** * Add a per retry policy. * @param httpPipelinePolicy the retry policy to be added. * @return the updated client options */ public IdentityClientOptions addPerRetryPolicy(HttpPipelinePolicy httpPipelinePolicy) { this.perRetryPolicies.add(httpPipelinePolicy); return this; } /** * Get the configured per retry policies. * @return the per retry policies. */ public List<HttpPipelinePolicy> getPerRetryPolicies() { return this.perRetryPolicies; } /** * Get the configured per call policies. * @return the per call policies. */ public List<HttpPipelinePolicy> getPerCallPolicies() { return this.perCallPolicies; } IdentityClientOptions setCp1Disabled(boolean cp1Disabled) { this.cp1Disabled = cp1Disabled; return this; } IdentityClientOptions setMultiTenantAuthDisabled(boolean multiTenantAuthDisabled) { this.multiTenantAuthDisabled = multiTenantAuthDisabled; return this; } IdentityClientOptions setAdditionallyAllowedTenants(Set<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = additionallyAllowedTenants; return this; } /** * Specifies either the specific regional authority, or use {@link RegionalAuthority * * @param regionalAuthority the regional authority * @return the updated identity client options */ IdentityClientOptions setRegionalAuthority(RegionalAuthority regionalAuthority) { this.regionalAuthority = regionalAuthority; return this; } IdentityClientOptions setConfigurationStore(Configuration configuration) { this.configuration = configuration; return this; } IdentityClientOptions setUserAssertion(UserAssertion userAssertion) { this.userAssertion = userAssertion; return this; } IdentityClientOptions setPersistenceCache(boolean persistenceCache) { this.sharedTokenCacheEnabled = persistenceCache; return this; } IdentityClientOptions setImdsAuthorityHost(String imdsAuthorityHost) { this.imdsAuthorityHost = imdsAuthorityHost; return this; } IdentityClientOptions setPerCallPolicies(List<HttpPipelinePolicy> perCallPolicies) { this.perCallPolicies = perCallPolicies; return this; } IdentityClientOptions setPerRetryPolicies(List<HttpPipelinePolicy> perRetryPolicies) { this.perRetryPolicies = perRetryPolicies; return this; } /** * Disables authority validation and instance discovery. * Instance discovery is acquiring metadata about an authority from https: * to validate that authority. This may need to be disabled in private cloud or ADFS scenarios. * * @return the updated client options */ public IdentityClientOptions disableInstanceDiscovery() { this.instanceDiscovery = false; return this; } /** * Gets the instance discovery policy. * @return boolean indicating if instance discovery is enabled. */ public boolean isInstanceDiscoveryEnabled() { return this.instanceDiscovery; } /** * Loads the details from the specified Configuration Store. */ private void loadFromConfiguration(Configuration configuration) { authorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); imdsAuthorityHost = configuration.get(AZURE_POD_IDENTITY_AUTHORITY_HOST, IdentityConstants.DEFAULT_IMDS_ENDPOINT); ValidationUtil.validateAuthHost(authorityHost, LOGGER); cp1Disabled = configuration.get(Configuration.PROPERTY_AZURE_IDENTITY_DISABLE_CP1, false); multiTenantAuthDisabled = configuration .get(AZURE_IDENTITY_DISABLE_MULTI_TENANT_AUTH, false); } /** * Gets the timeout to apply to developer credential operations. * @return The timeout value for developer credential operations. */ public Duration getCredentialProcessTimeout() { return credentialProcessTimeout; } /** * Sets the timeout for developer credential operations. * @param credentialProcessTimeout The timeout value for developer credential operations. */ public void setCredentialProcessTimeout(Duration credentialProcessTimeout) { this.credentialProcessTimeout = credentialProcessTimeout; } /** * Indicates whether this options instance is part of a {@link ChainedTokenCredential}. * @return true if this options instance is part of a {@link ChainedTokenCredential}, false otherwise. */ public boolean isChained() { return this.isChained; } /** * Sets whether this options instance is part of a {@link ChainedTokenCredential}. * @param isChained * @return the updated client options */ public IdentityClientOptions setChained(boolean isChained) { this.isChained = isChained; return this; } }
could you re-try, without this line?
public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); logAnalyticsManager = LogAnalyticsManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); networkManager = NetworkManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); workloadsManager = WorkloadsManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .authenticate(credential, profile); resourceManager = ResourceManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile) .withDefaultSubscription(); resourceManager.resourceGroups().define(MANAGED_RG_NAME).withRegion(MANAGED_REGION).create(); String testResourceGroup = Configuration.getGlobalConfiguration().get("AZURE_RESOURCE_GROUP_NAME"); testEnv = !CoreUtils.isNullOrEmpty(testResourceGroup); if (testEnv) { resourceGroupName = testResourceGroup; } else { resourceManager.resourceGroups() .define(resourceGroupName) .withRegion(RESOURCE_REGION) .create(); } }
resourceManager.resourceGroups().define(MANAGED_RG_NAME).withRegion(MANAGED_REGION).create();
public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); logAnalyticsManager = LogAnalyticsManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); networkManager = NetworkManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); workloadsManager = WorkloadsManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .authenticate(credential, profile); resourceManager = ResourceManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile) .withDefaultSubscription(); String testResourceGroup = Configuration.getGlobalConfiguration().get("AZURE_RESOURCE_GROUP_NAME"); testEnv = !CoreUtils.isNullOrEmpty(testResourceGroup); if (testEnv) { resourceGroupName = testResourceGroup; } else { resourceManager.resourceGroups() .define(resourceGroupName) .withRegion(RESOURCE_REGION) .create(); } }
class WorkloadsManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region RESOURCE_REGION = Region.US_EAST2; private static final Region MANAGED_REGION = Region.US_EAST; private static final Region APPLICATION_REGION = Region.US_WEST; private static final String MANAGED_RG_NAME = "managerRG" + randomPadding(); private String resourceGroupName = "rg" + randomPadding(); private LogAnalyticsManager logAnalyticsManager; private NetworkManager networkManager; private WorkloadsManager workloadsManager; private ResourceManager resourceManager; private boolean testEnv; @Override @Override protected void afterTest() { resourceManager.resourceGroups().beginDeleteByName(MANAGED_RG_NAME); if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) public void testCreateMonitor() { Monitor monitor = null; String randomPadding = randomPadding(); try { String monitorName = "monitor" + randomPadding; String vNetworkName = "network" + randomPadding; String workspaceName = "workspace" + randomPadding; monitor = workloadsManager.monitors() .define(monitorName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withAppLocation(APPLICATION_REGION.name()) .withRoutingPreference(RoutingPreference.ROUTE_ALL) .withManagedResourceGroupConfiguration( new ManagedRGConfiguration().withName(MANAGED_RG_NAME)) .withLogAnalyticsWorkspaceArmId( logAnalyticsManager.workspaces() .define(workspaceName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new WorkspaceSku() .withName(WorkspaceSkuNameEnum.PER_GB2018)) .withFeatures(new WorkspaceFeatures() .withEnableLogAccessUsingOnlyResourcePermissions(true)) .withRetentionInDays(30) .withWorkspaceCapping(new WorkspaceCapping().withDailyQuotaGb(-1D)) .withPublicNetworkAccessForIngestion(PublicNetworkAccessType.ENABLED) .withPublicNetworkAccessForQuery(PublicNetworkAccessType.ENABLED) .create() .id()) .withMonitorSubnet( networkManager.networks() .define(vNetworkName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withAddressSpace("172.29.0.0/16") .withSubnet("default", "172.29.0.0/24") .create() .id()) .create(); monitor.refresh(); Assertions.assertEquals(monitor.name(), monitorName); Assertions.assertEquals(monitor.name(), workloadsManager.monitors().getById(monitor.id()).name()); Assertions.assertTrue(workloadsManager.monitors().list().stream().count() > 0); } finally { if (monitor != null) { workloadsManager.monitors().deleteById(monitor.id()); } } } private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class WorkloadsManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region RESOURCE_REGION = Region.US_EAST2; private static final Region APPLICATION_REGION = Region.US_WEST; private static final String MANAGED_RG_NAME = "managerRG" + randomPadding(); private String resourceGroupName = "rg" + randomPadding(); private LogAnalyticsManager logAnalyticsManager; private NetworkManager networkManager; private WorkloadsManager workloadsManager; private ResourceManager resourceManager; private boolean testEnv; @Override @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) public void testCreateMonitor() { Monitor monitor = null; String randomPadding = randomPadding(); try { String monitorName = "monitor" + randomPadding; String vNetworkName = "network" + randomPadding; String workspaceName = "workspace" + randomPadding; monitor = workloadsManager.monitors() .define(monitorName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withAppLocation(APPLICATION_REGION.name()) .withRoutingPreference(RoutingPreference.ROUTE_ALL) .withManagedResourceGroupConfiguration( new ManagedRGConfiguration().withName(MANAGED_RG_NAME)) .withLogAnalyticsWorkspaceArmId( logAnalyticsManager.workspaces() .define(workspaceName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new WorkspaceSku() .withName(WorkspaceSkuNameEnum.PER_GB2018)) .withFeatures(new WorkspaceFeatures() .withEnableLogAccessUsingOnlyResourcePermissions(true)) .withRetentionInDays(30) .withWorkspaceCapping(new WorkspaceCapping().withDailyQuotaGb(-1D)) .withPublicNetworkAccessForIngestion(PublicNetworkAccessType.ENABLED) .withPublicNetworkAccessForQuery(PublicNetworkAccessType.ENABLED) .create() .id()) .withMonitorSubnet( networkManager.networks() .define(vNetworkName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withAddressSpace("172.29.0.0/16") .withSubnet("default", "172.29.0.0/24") .create() .id()) .create(); monitor.refresh(); Assertions.assertEquals(monitor.name(), monitorName); Assertions.assertEquals(monitor.name(), workloadsManager.monitors().getById(monitor.id()).name()); Assertions.assertTrue(workloadsManager.monitors().list().stream().count() > 0); } finally { if (monitor != null) { workloadsManager.monitors().deleteById(monitor.id()); } } } private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
`ResourceGroupNotFound` exception occrus when without this line, the detail infomation check [here](https://github.com/Azure/azure-sdk-for-java/files/12010990/workloads-live-test.log)
public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); logAnalyticsManager = LogAnalyticsManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); networkManager = NetworkManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); workloadsManager = WorkloadsManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .authenticate(credential, profile); resourceManager = ResourceManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile) .withDefaultSubscription(); resourceManager.resourceGroups().define(MANAGED_RG_NAME).withRegion(MANAGED_REGION).create(); String testResourceGroup = Configuration.getGlobalConfiguration().get("AZURE_RESOURCE_GROUP_NAME"); testEnv = !CoreUtils.isNullOrEmpty(testResourceGroup); if (testEnv) { resourceGroupName = testResourceGroup; } else { resourceManager.resourceGroups() .define(resourceGroupName) .withRegion(RESOURCE_REGION) .create(); } }
resourceManager.resourceGroups().define(MANAGED_RG_NAME).withRegion(MANAGED_REGION).create();
public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); logAnalyticsManager = LogAnalyticsManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); networkManager = NetworkManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); workloadsManager = WorkloadsManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .authenticate(credential, profile); resourceManager = ResourceManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile) .withDefaultSubscription(); String testResourceGroup = Configuration.getGlobalConfiguration().get("AZURE_RESOURCE_GROUP_NAME"); testEnv = !CoreUtils.isNullOrEmpty(testResourceGroup); if (testEnv) { resourceGroupName = testResourceGroup; } else { resourceManager.resourceGroups() .define(resourceGroupName) .withRegion(RESOURCE_REGION) .create(); } }
class WorkloadsManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region RESOURCE_REGION = Region.US_EAST2; private static final Region MANAGED_REGION = Region.US_EAST; private static final Region APPLICATION_REGION = Region.US_WEST; private static final String MANAGED_RG_NAME = "managerRG" + randomPadding(); private String resourceGroupName = "rg" + randomPadding(); private LogAnalyticsManager logAnalyticsManager; private NetworkManager networkManager; private WorkloadsManager workloadsManager; private ResourceManager resourceManager; private boolean testEnv; @Override @Override protected void afterTest() { resourceManager.resourceGroups().beginDeleteByName(MANAGED_RG_NAME); if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) public void testCreateMonitor() { Monitor monitor = null; String randomPadding = randomPadding(); try { String monitorName = "monitor" + randomPadding; String vNetworkName = "network" + randomPadding; String workspaceName = "workspace" + randomPadding; monitor = workloadsManager.monitors() .define(monitorName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withAppLocation(APPLICATION_REGION.name()) .withRoutingPreference(RoutingPreference.ROUTE_ALL) .withManagedResourceGroupConfiguration( new ManagedRGConfiguration().withName(MANAGED_RG_NAME)) .withLogAnalyticsWorkspaceArmId( logAnalyticsManager.workspaces() .define(workspaceName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new WorkspaceSku() .withName(WorkspaceSkuNameEnum.PER_GB2018)) .withFeatures(new WorkspaceFeatures() .withEnableLogAccessUsingOnlyResourcePermissions(true)) .withRetentionInDays(30) .withWorkspaceCapping(new WorkspaceCapping().withDailyQuotaGb(-1D)) .withPublicNetworkAccessForIngestion(PublicNetworkAccessType.ENABLED) .withPublicNetworkAccessForQuery(PublicNetworkAccessType.ENABLED) .create() .id()) .withMonitorSubnet( networkManager.networks() .define(vNetworkName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withAddressSpace("172.29.0.0/16") .withSubnet("default", "172.29.0.0/24") .create() .id()) .create(); monitor.refresh(); Assertions.assertEquals(monitor.name(), monitorName); Assertions.assertEquals(monitor.name(), workloadsManager.monitors().getById(monitor.id()).name()); Assertions.assertTrue(workloadsManager.monitors().list().stream().count() > 0); } finally { if (monitor != null) { workloadsManager.monitors().deleteById(monitor.id()); } } } private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class WorkloadsManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region RESOURCE_REGION = Region.US_EAST2; private static final Region APPLICATION_REGION = Region.US_WEST; private static final String MANAGED_RG_NAME = "managerRG" + randomPadding(); private String resourceGroupName = "rg" + randomPadding(); private LogAnalyticsManager logAnalyticsManager; private NetworkManager networkManager; private WorkloadsManager workloadsManager; private ResourceManager resourceManager; private boolean testEnv; @Override @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) public void testCreateMonitor() { Monitor monitor = null; String randomPadding = randomPadding(); try { String monitorName = "monitor" + randomPadding; String vNetworkName = "network" + randomPadding; String workspaceName = "workspace" + randomPadding; monitor = workloadsManager.monitors() .define(monitorName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withAppLocation(APPLICATION_REGION.name()) .withRoutingPreference(RoutingPreference.ROUTE_ALL) .withManagedResourceGroupConfiguration( new ManagedRGConfiguration().withName(MANAGED_RG_NAME)) .withLogAnalyticsWorkspaceArmId( logAnalyticsManager.workspaces() .define(workspaceName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new WorkspaceSku() .withName(WorkspaceSkuNameEnum.PER_GB2018)) .withFeatures(new WorkspaceFeatures() .withEnableLogAccessUsingOnlyResourcePermissions(true)) .withRetentionInDays(30) .withWorkspaceCapping(new WorkspaceCapping().withDailyQuotaGb(-1D)) .withPublicNetworkAccessForIngestion(PublicNetworkAccessType.ENABLED) .withPublicNetworkAccessForQuery(PublicNetworkAccessType.ENABLED) .create() .id()) .withMonitorSubnet( networkManager.networks() .define(vNetworkName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withAddressSpace("172.29.0.0/16") .withSubnet("default", "172.29.0.0/24") .create() .id()) .create(); monitor.refresh(); Assertions.assertEquals(monitor.name(), monitorName); Assertions.assertEquals(monitor.name(), workloadsManager.monitors().getById(monitor.id()).name()); Assertions.assertTrue(workloadsManager.monitors().list().stream().count() > 0); } finally { if (monitor != null) { workloadsManager.monitors().deleteById(monitor.id()); } } } private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
error could happen because of any reason, we should change the error message to generic message, like -> ```suggestion throwable -> System.out.printf("Failed to create container: " + throwable) ```
public void databaseCreateContainerAsyncSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); cosmosAsyncDatabase.createContainer(containerProperties) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.printf("Container with id : %s already exists \n", containerId) ); }
throwable -> System.out.printf("Container with id : %s already exists \n", containerId)
public void databaseCreateContainerAsyncSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); cosmosAsyncDatabase.createContainer(containerProperties) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.println("Failed to create container: " + throwable) ); }
class AsyncContainerCodeSnippets { private final CosmosAsyncClient cosmosAsyncClient = new CosmosClientBuilder() .endpoint("<YOUR ENDPOINT HERE>") .key("<YOUR KEY HERE>") .buildAsyncClient(); private final CosmosClient cosmosClient = new CosmosClientBuilder() .endpoint("<YOUR ENDPOINT HERE>") .key("<YOUR KEY HERE>") .buildClient(); private final CosmosAsyncDatabase cosmosAsyncDatabase = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); private final CosmosAsyncContainer cosmosAsyncContainer = cosmosAsyncDatabase .getContainer("<YOUR CONTAINER NAME>"); private final CosmosContainer cosmosContainer = cosmosClient .getDatabase("<YOUR DATABASE NAME>") .getContainer("<YOUR CONTAINER NAME>"); public void getFeedRangesAsyncSample() { cosmosAsyncContainer.getFeedRanges() .subscribe(feedRanges -> { for (FeedRange feedRange : feedRanges) { System.out.println("Feed range: " + feedRange); } }); } public void getFeedRangesSample() { List<FeedRange> feedRanges = cosmosContainer.getFeedRanges(); for (FeedRange feedRange : feedRanges) { System.out.println("Feed range: " + feedRange); } } public void readThroughputAsyncSample() { Mono<ThroughputResponse> throughputResponseMono = cosmosAsyncContainer.readThroughput(); throughputResponseMono.subscribe(throughputResponse -> { System.out.println(throughputResponse); }, throwable -> { throwable.printStackTrace(); }); } public void readThroughputSample() { try { ThroughputResponse throughputResponse = cosmosContainer.readThroughput(); System.out.println(throughputResponse); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void replaceThroughputAsyncSample() { ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(1000); cosmosAsyncContainer.replaceThroughput(throughputProperties) .subscribe(throughputResponse -> { System.out.println(throughputResponse); }, throwable -> { throwable.printStackTrace(); }); } public void replaceThroughputSample() { ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(1000); try { ThroughputResponse throughputResponse = cosmosContainer.replaceThroughput(throughputProperties); System.out.println(throughputResponse); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void queryConflictsAsyncSample() { List<String> conflictIds = Collections.emptyList(); String query = "SELECT * from c where c.id in (%s)"; try { cosmosAsyncContainer.queryConflicts(query). byPage(100) .subscribe(response -> { for (CosmosConflictProperties conflictProperties : response.getResults()) { System.out.println(conflictProperties); } }, throwable -> { throwable.printStackTrace(); }); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void readAllConflictsAsyncSample() { List<String> conflictIds = Collections.emptyList(); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); try { cosmosAsyncContainer.readAllConflicts(options). byPage(100) .subscribe(response -> { for (CosmosConflictProperties conflictProperties : response.getResults()) { System.out.println(conflictProperties); } }, throwable -> { throwable.printStackTrace(); }); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void patchItemAsyncSample() { Passenger passenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); CosmosPatchOperations cosmosPatchOperations = CosmosPatchOperations.create(); cosmosPatchOperations .add("/departure", "SEA") .increment("/trips", 1); cosmosAsyncContainer.patchItem( passenger.getId(), new PartitionKey(passenger.getId()), cosmosPatchOperations, Passenger.class) .subscribe(response -> { System.out.println(response); }, throwable -> { throwable.printStackTrace(); }); } public void replaceItemAsyncSample() { Passenger oldPassenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); Passenger newPassenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); cosmosAsyncContainer.replaceItem( newPassenger, oldPassenger.getId(), new PartitionKey(oldPassenger.getId()), new CosmosItemRequestOptions()) .subscribe(response -> { System.out.println(response); }, throwable -> { throwable.printStackTrace(); }); } public void readAllItemsAsyncSample() { String partitionKey = "partitionKey"; cosmosAsyncContainer .readAllItems(new PartitionKey(partitionKey), Passenger.class) .byPage(100) .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void readManyAsyncSample() { String passenger1Id = "item1"; String passenger2Id = "item1"; List<CosmosItemIdentity> itemIdentityList = new ArrayList<>(); itemIdentityList.add(new CosmosItemIdentity(new PartitionKey(passenger1Id), passenger1Id)); itemIdentityList.add(new CosmosItemIdentity(new PartitionKey(passenger2Id), passenger2Id)); cosmosAsyncContainer.readMany(itemIdentityList, Passenger.class) .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Mono.empty(); }) .subscribe(); } public void queryChangeFeedSample() { CosmosChangeFeedRequestOptions options = CosmosChangeFeedRequestOptions .createForProcessingFromNow(FeedRange.forFullRange()) .allVersionsAndDeletes(); cosmosAsyncContainer.queryChangeFeed(options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void queryItemsAsyncSample() { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); String query = "SELECT * FROM Passenger WHERE Passenger.departure IN ('SEA', 'IND')"; cosmosAsyncContainer.queryItems(query, options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void queryItemsAsyncSqlQuerySpecSample() { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); String query = "SELECT * FROM Passenger p WHERE (p.departure = @departure)"; List<SqlParameter> parameters = Collections.singletonList(new SqlParameter("@departure", "SEA")); SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(query, parameters); cosmosAsyncContainer.queryItems(sqlQuerySpec, options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void databaseReadAsyncSample() { CosmosAsyncDatabase database = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); database.read().subscribe(databaseResponse -> { System.out.println(databaseResponse); }, throwable -> { throwable.printStackTrace(); }); } public void databaseDeleteAsyncSample() { CosmosAsyncDatabase database = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); database.delete().subscribe(databaseResponse -> { System.out.println(databaseResponse); }, throwable -> { throwable.printStackTrace(); }); } public void databaseCreateContainerPropsSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); int autoScaleMaxThroughput = 1000; CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(autoScaleMaxThroughput); cosmosAsyncDatabase.createContainer(containerProperties, throughputProperties) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.printf("Container with id : %s already exists \n", containerId) ); } public void databaseCreateContainerThroughputSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); int throughput = 1000; CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); cosmosAsyncDatabase.createContainer( containerProperties, throughput, options ) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.printf("Container with id : %s already exists \n", containerId) ); } public void databaseCreateContainerPartitionKeyAsyncSample() { String containerId = "passengers"; String partitionKeyPath = "/id"; int autoscaledThroughput = 1000; ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(autoscaledThroughput); cosmosAsyncDatabase.createContainer( containerId, partitionKeyPath, throughputProperties ) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.printf("Container with id : %s already exists \n", containerId) ); } }
class AsyncContainerCodeSnippets { private final CosmosAsyncClient cosmosAsyncClient = new CosmosClientBuilder() .endpoint("<YOUR ENDPOINT HERE>") .key("<YOUR KEY HERE>") .buildAsyncClient(); private final CosmosClient cosmosClient = new CosmosClientBuilder() .endpoint("<YOUR ENDPOINT HERE>") .key("<YOUR KEY HERE>") .buildClient(); private final CosmosAsyncDatabase cosmosAsyncDatabase = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); private final CosmosAsyncContainer cosmosAsyncContainer = cosmosAsyncDatabase .getContainer("<YOUR CONTAINER NAME>"); private final CosmosContainer cosmosContainer = cosmosClient .getDatabase("<YOUR DATABASE NAME>") .getContainer("<YOUR CONTAINER NAME>"); public void getFeedRangesAsyncSample() { cosmosAsyncContainer.getFeedRanges() .subscribe(feedRanges -> { for (FeedRange feedRange : feedRanges) { System.out.println("Feed range: " + feedRange); } }); } public void getFeedRangesSample() { List<FeedRange> feedRanges = cosmosContainer.getFeedRanges(); for (FeedRange feedRange : feedRanges) { System.out.println("Feed range: " + feedRange); } } public void readThroughputAsyncSample() { Mono<ThroughputResponse> throughputResponseMono = cosmosAsyncContainer.readThroughput(); throughputResponseMono.subscribe(throughputResponse -> { System.out.println(throughputResponse); }, throwable -> { throwable.printStackTrace(); }); } public void readThroughputSample() { try { ThroughputResponse throughputResponse = cosmosContainer.readThroughput(); System.out.println(throughputResponse); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void replaceThroughputAsyncSample() { ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(1000); cosmosAsyncContainer.replaceThroughput(throughputProperties) .subscribe(throughputResponse -> { System.out.println(throughputResponse); }, throwable -> { throwable.printStackTrace(); }); } public void replaceThroughputSample() { ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(1000); try { ThroughputResponse throughputResponse = cosmosContainer.replaceThroughput(throughputProperties); System.out.println(throughputResponse); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void queryConflictsAsyncSample() { List<String> conflictIds = Collections.emptyList(); String query = "SELECT * from c where c.id in (%s)"; try { cosmosAsyncContainer.queryConflicts(query). byPage(100) .subscribe(response -> { for (CosmosConflictProperties conflictProperties : response.getResults()) { System.out.println(conflictProperties); } }, throwable -> { throwable.printStackTrace(); }); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void readAllConflictsAsyncSample() { List<String> conflictIds = Collections.emptyList(); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); try { cosmosAsyncContainer.readAllConflicts(options). byPage(100) .subscribe(response -> { for (CosmosConflictProperties conflictProperties : response.getResults()) { System.out.println(conflictProperties); } }, throwable -> { throwable.printStackTrace(); }); } catch (CosmosException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void patchItemAsyncSample() { Passenger passenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); CosmosPatchOperations cosmosPatchOperations = CosmosPatchOperations.create(); cosmosPatchOperations .add("/departure", "SEA") .increment("/trips", 1); cosmosAsyncContainer.patchItem( passenger.getId(), new PartitionKey(passenger.getId()), cosmosPatchOperations, Passenger.class) .subscribe(response -> { System.out.println(response); }, throwable -> { throwable.printStackTrace(); }); } public void replaceItemAsyncSample() { Passenger oldPassenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); Passenger newPassenger = new Passenger("carla.davis@outlook.com", "Carla Davis", "SEA", "IND"); cosmosAsyncContainer.replaceItem( newPassenger, oldPassenger.getId(), new PartitionKey(oldPassenger.getId()), new CosmosItemRequestOptions()) .subscribe(response -> { System.out.println(response); }, throwable -> { throwable.printStackTrace(); }); } public void readAllItemsAsyncSample() { String partitionKey = "partitionKey"; cosmosAsyncContainer .readAllItems(new PartitionKey(partitionKey), Passenger.class) .byPage(100) .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void readManyAsyncSample() { String passenger1Id = "item1"; String passenger2Id = "item1"; List<CosmosItemIdentity> itemIdentityList = new ArrayList<>(); itemIdentityList.add(new CosmosItemIdentity(new PartitionKey(passenger1Id), passenger1Id)); itemIdentityList.add(new CosmosItemIdentity(new PartitionKey(passenger2Id), passenger2Id)); cosmosAsyncContainer.readMany(itemIdentityList, Passenger.class) .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Mono.empty(); }) .subscribe(); } public void queryChangeFeedSample() { CosmosChangeFeedRequestOptions options = CosmosChangeFeedRequestOptions .createForProcessingFromNow(FeedRange.forFullRange()) .allVersionsAndDeletes(); cosmosAsyncContainer.queryChangeFeed(options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void queryItemsAsyncSample() { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); String query = "SELECT * FROM Passenger WHERE Passenger.departure IN ('SEA', 'IND')"; cosmosAsyncContainer.queryItems(query, options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void queryItemsAsyncSqlQuerySpecSample() { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); String query = "SELECT * FROM Passenger p WHERE (p.departure = @departure)"; List<SqlParameter> parameters = Collections.singletonList(new SqlParameter("@departure", "SEA")); SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(query, parameters); cosmosAsyncContainer.queryItems(sqlQuerySpec, options, Passenger.class) .byPage() .flatMap(passengerFeedResponse -> { for (Passenger passenger : passengerFeedResponse.getResults()) { System.out.println(passenger); } return Flux.empty(); }) .subscribe(); } public void databaseReadAsyncSample() { CosmosAsyncDatabase database = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); database.read().subscribe(databaseResponse -> { System.out.println(databaseResponse); }, throwable -> { throwable.printStackTrace(); }); } public void databaseDeleteAsyncSample() { CosmosAsyncDatabase database = cosmosAsyncClient .getDatabase("<YOUR DATABASE NAME>"); database.delete().subscribe(databaseResponse -> { System.out.println(databaseResponse); }, throwable -> { throwable.printStackTrace(); }); } public void databaseCreateContainerPropsSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); int autoScaleMaxThroughput = 1000; CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(autoScaleMaxThroughput); cosmosAsyncDatabase.createContainer(containerProperties, throughputProperties) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.println("Failed to create container: " + throwable) ); } public void databaseCreateContainerThroughputSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); int throughput = 1000; CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); cosmosAsyncDatabase.createContainer( containerProperties, throughput, options ) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.println("Failed to create container: " + throwable) ); } public void databaseCreateContainerPartitionKeyAsyncSample() { String containerId = "passengers"; String partitionKeyPath = "/id"; int autoscaledThroughput = 1000; ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaledThroughput(autoscaledThroughput); cosmosAsyncDatabase.createContainer( containerId, partitionKeyPath, throughputProperties ) .subscribe( cosmosContainerResponse -> System.out.println(cosmosContainerResponse), throwable -> System.out.println("Failed to create container: " + throwable) ); } }
because you are deleting it here ``` resourceManager.resourceGroups().beginDeleteByName(MANAGED_RG_NAME); ```
public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); logAnalyticsManager = LogAnalyticsManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); networkManager = NetworkManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); workloadsManager = WorkloadsManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .authenticate(credential, profile); resourceManager = ResourceManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile) .withDefaultSubscription(); resourceManager.resourceGroups().define(MANAGED_RG_NAME).withRegion(MANAGED_REGION).create(); String testResourceGroup = Configuration.getGlobalConfiguration().get("AZURE_RESOURCE_GROUP_NAME"); testEnv = !CoreUtils.isNullOrEmpty(testResourceGroup); if (testEnv) { resourceGroupName = testResourceGroup; } else { resourceManager.resourceGroups() .define(resourceGroupName) .withRegion(RESOURCE_REGION) .create(); } }
resourceManager.resourceGroups().define(MANAGED_RG_NAME).withRegion(MANAGED_REGION).create();
public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); logAnalyticsManager = LogAnalyticsManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); networkManager = NetworkManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); workloadsManager = WorkloadsManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .authenticate(credential, profile); resourceManager = ResourceManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile) .withDefaultSubscription(); String testResourceGroup = Configuration.getGlobalConfiguration().get("AZURE_RESOURCE_GROUP_NAME"); testEnv = !CoreUtils.isNullOrEmpty(testResourceGroup); if (testEnv) { resourceGroupName = testResourceGroup; } else { resourceManager.resourceGroups() .define(resourceGroupName) .withRegion(RESOURCE_REGION) .create(); } }
class WorkloadsManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region RESOURCE_REGION = Region.US_EAST2; private static final Region MANAGED_REGION = Region.US_EAST; private static final Region APPLICATION_REGION = Region.US_WEST; private static final String MANAGED_RG_NAME = "managerRG" + randomPadding(); private String resourceGroupName = "rg" + randomPadding(); private LogAnalyticsManager logAnalyticsManager; private NetworkManager networkManager; private WorkloadsManager workloadsManager; private ResourceManager resourceManager; private boolean testEnv; @Override @Override protected void afterTest() { resourceManager.resourceGroups().beginDeleteByName(MANAGED_RG_NAME); if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) public void testCreateMonitor() { Monitor monitor = null; String randomPadding = randomPadding(); try { String monitorName = "monitor" + randomPadding; String vNetworkName = "network" + randomPadding; String workspaceName = "workspace" + randomPadding; monitor = workloadsManager.monitors() .define(monitorName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withAppLocation(APPLICATION_REGION.name()) .withRoutingPreference(RoutingPreference.ROUTE_ALL) .withManagedResourceGroupConfiguration( new ManagedRGConfiguration().withName(MANAGED_RG_NAME)) .withLogAnalyticsWorkspaceArmId( logAnalyticsManager.workspaces() .define(workspaceName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new WorkspaceSku() .withName(WorkspaceSkuNameEnum.PER_GB2018)) .withFeatures(new WorkspaceFeatures() .withEnableLogAccessUsingOnlyResourcePermissions(true)) .withRetentionInDays(30) .withWorkspaceCapping(new WorkspaceCapping().withDailyQuotaGb(-1D)) .withPublicNetworkAccessForIngestion(PublicNetworkAccessType.ENABLED) .withPublicNetworkAccessForQuery(PublicNetworkAccessType.ENABLED) .create() .id()) .withMonitorSubnet( networkManager.networks() .define(vNetworkName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withAddressSpace("172.29.0.0/16") .withSubnet("default", "172.29.0.0/24") .create() .id()) .create(); monitor.refresh(); Assertions.assertEquals(monitor.name(), monitorName); Assertions.assertEquals(monitor.name(), workloadsManager.monitors().getById(monitor.id()).name()); Assertions.assertTrue(workloadsManager.monitors().list().stream().count() > 0); } finally { if (monitor != null) { workloadsManager.monitors().deleteById(monitor.id()); } } } private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class WorkloadsManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region RESOURCE_REGION = Region.US_EAST2; private static final Region APPLICATION_REGION = Region.US_WEST; private static final String MANAGED_RG_NAME = "managerRG" + randomPadding(); private String resourceGroupName = "rg" + randomPadding(); private LogAnalyticsManager logAnalyticsManager; private NetworkManager networkManager; private WorkloadsManager workloadsManager; private ResourceManager resourceManager; private boolean testEnv; @Override @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) public void testCreateMonitor() { Monitor monitor = null; String randomPadding = randomPadding(); try { String monitorName = "monitor" + randomPadding; String vNetworkName = "network" + randomPadding; String workspaceName = "workspace" + randomPadding; monitor = workloadsManager.monitors() .define(monitorName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withAppLocation(APPLICATION_REGION.name()) .withRoutingPreference(RoutingPreference.ROUTE_ALL) .withManagedResourceGroupConfiguration( new ManagedRGConfiguration().withName(MANAGED_RG_NAME)) .withLogAnalyticsWorkspaceArmId( logAnalyticsManager.workspaces() .define(workspaceName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new WorkspaceSku() .withName(WorkspaceSkuNameEnum.PER_GB2018)) .withFeatures(new WorkspaceFeatures() .withEnableLogAccessUsingOnlyResourcePermissions(true)) .withRetentionInDays(30) .withWorkspaceCapping(new WorkspaceCapping().withDailyQuotaGb(-1D)) .withPublicNetworkAccessForIngestion(PublicNetworkAccessType.ENABLED) .withPublicNetworkAccessForQuery(PublicNetworkAccessType.ENABLED) .create() .id()) .withMonitorSubnet( networkManager.networks() .define(vNetworkName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withAddressSpace("172.29.0.0/16") .withSubnet("default", "172.29.0.0/24") .create() .id()) .create(); monitor.refresh(); Assertions.assertEquals(monitor.name(), monitorName); Assertions.assertEquals(monitor.name(), workloadsManager.monitors().getById(monitor.id()).name()); Assertions.assertTrue(workloadsManager.monitors().list().stream().count() > 0); } finally { if (monitor != null) { workloadsManager.monitors().deleteById(monitor.id()); } } } private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
The `MANAGED_RG_NAME` related code has been removed in the new version.
public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); logAnalyticsManager = LogAnalyticsManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); networkManager = NetworkManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); workloadsManager = WorkloadsManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .authenticate(credential, profile); resourceManager = ResourceManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile) .withDefaultSubscription(); resourceManager.resourceGroups().define(MANAGED_RG_NAME).withRegion(MANAGED_REGION).create(); String testResourceGroup = Configuration.getGlobalConfiguration().get("AZURE_RESOURCE_GROUP_NAME"); testEnv = !CoreUtils.isNullOrEmpty(testResourceGroup); if (testEnv) { resourceGroupName = testResourceGroup; } else { resourceManager.resourceGroups() .define(resourceGroupName) .withRegion(RESOURCE_REGION) .create(); } }
resourceManager.resourceGroups().define(MANAGED_RG_NAME).withRegion(MANAGED_REGION).create();
public void beforeTest() { final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); logAnalyticsManager = LogAnalyticsManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); networkManager = NetworkManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile); workloadsManager = WorkloadsManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .authenticate(credential, profile); resourceManager = ResourceManager .configure() .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) .authenticate(credential, profile) .withDefaultSubscription(); String testResourceGroup = Configuration.getGlobalConfiguration().get("AZURE_RESOURCE_GROUP_NAME"); testEnv = !CoreUtils.isNullOrEmpty(testResourceGroup); if (testEnv) { resourceGroupName = testResourceGroup; } else { resourceManager.resourceGroups() .define(resourceGroupName) .withRegion(RESOURCE_REGION) .create(); } }
class WorkloadsManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region RESOURCE_REGION = Region.US_EAST2; private static final Region MANAGED_REGION = Region.US_EAST; private static final Region APPLICATION_REGION = Region.US_WEST; private static final String MANAGED_RG_NAME = "managerRG" + randomPadding(); private String resourceGroupName = "rg" + randomPadding(); private LogAnalyticsManager logAnalyticsManager; private NetworkManager networkManager; private WorkloadsManager workloadsManager; private ResourceManager resourceManager; private boolean testEnv; @Override @Override protected void afterTest() { resourceManager.resourceGroups().beginDeleteByName(MANAGED_RG_NAME); if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) public void testCreateMonitor() { Monitor monitor = null; String randomPadding = randomPadding(); try { String monitorName = "monitor" + randomPadding; String vNetworkName = "network" + randomPadding; String workspaceName = "workspace" + randomPadding; monitor = workloadsManager.monitors() .define(monitorName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withAppLocation(APPLICATION_REGION.name()) .withRoutingPreference(RoutingPreference.ROUTE_ALL) .withManagedResourceGroupConfiguration( new ManagedRGConfiguration().withName(MANAGED_RG_NAME)) .withLogAnalyticsWorkspaceArmId( logAnalyticsManager.workspaces() .define(workspaceName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new WorkspaceSku() .withName(WorkspaceSkuNameEnum.PER_GB2018)) .withFeatures(new WorkspaceFeatures() .withEnableLogAccessUsingOnlyResourcePermissions(true)) .withRetentionInDays(30) .withWorkspaceCapping(new WorkspaceCapping().withDailyQuotaGb(-1D)) .withPublicNetworkAccessForIngestion(PublicNetworkAccessType.ENABLED) .withPublicNetworkAccessForQuery(PublicNetworkAccessType.ENABLED) .create() .id()) .withMonitorSubnet( networkManager.networks() .define(vNetworkName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withAddressSpace("172.29.0.0/16") .withSubnet("default", "172.29.0.0/24") .create() .id()) .create(); monitor.refresh(); Assertions.assertEquals(monitor.name(), monitorName); Assertions.assertEquals(monitor.name(), workloadsManager.monitors().getById(monitor.id()).name()); Assertions.assertTrue(workloadsManager.monitors().list().stream().count() > 0); } finally { if (monitor != null) { workloadsManager.monitors().deleteById(monitor.id()); } } } private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
class WorkloadsManagerTests extends TestBase { private static final Random RANDOM = new Random(); private static final Region RESOURCE_REGION = Region.US_EAST2; private static final Region APPLICATION_REGION = Region.US_WEST; private static final String MANAGED_RG_NAME = "managerRG" + randomPadding(); private String resourceGroupName = "rg" + randomPadding(); private LogAnalyticsManager logAnalyticsManager; private NetworkManager networkManager; private WorkloadsManager workloadsManager; private ResourceManager resourceManager; private boolean testEnv; @Override @Override protected void afterTest() { if (!testEnv) { resourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } } @Test @DoNotRecord(skipInPlayback = true) public void testCreateMonitor() { Monitor monitor = null; String randomPadding = randomPadding(); try { String monitorName = "monitor" + randomPadding; String vNetworkName = "network" + randomPadding; String workspaceName = "workspace" + randomPadding; monitor = workloadsManager.monitors() .define(monitorName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withAppLocation(APPLICATION_REGION.name()) .withRoutingPreference(RoutingPreference.ROUTE_ALL) .withManagedResourceGroupConfiguration( new ManagedRGConfiguration().withName(MANAGED_RG_NAME)) .withLogAnalyticsWorkspaceArmId( logAnalyticsManager.workspaces() .define(workspaceName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withSku(new WorkspaceSku() .withName(WorkspaceSkuNameEnum.PER_GB2018)) .withFeatures(new WorkspaceFeatures() .withEnableLogAccessUsingOnlyResourcePermissions(true)) .withRetentionInDays(30) .withWorkspaceCapping(new WorkspaceCapping().withDailyQuotaGb(-1D)) .withPublicNetworkAccessForIngestion(PublicNetworkAccessType.ENABLED) .withPublicNetworkAccessForQuery(PublicNetworkAccessType.ENABLED) .create() .id()) .withMonitorSubnet( networkManager.networks() .define(vNetworkName) .withRegion(RESOURCE_REGION) .withExistingResourceGroup(resourceGroupName) .withAddressSpace("172.29.0.0/16") .withSubnet("default", "172.29.0.0/24") .create() .id()) .create(); monitor.refresh(); Assertions.assertEquals(monitor.name(), monitorName); Assertions.assertEquals(monitor.name(), workloadsManager.monitors().getById(monitor.id()).name()); Assertions.assertTrue(workloadsManager.monitors().list().stream().count() > 0); } finally { if (monitor != null) { workloadsManager.monitors().deleteById(monitor.id()); } } } private static String randomPadding() { return String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); } }
This aligns the code with the implementation of setSessionState (+ allows us to remove getSessionState in ServiceBusSessionManager which was duplicating the code)
private Mono<byte[]> getSessionState(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState"))); } else if (!isSessionEnabled) { return monoError(LOGGER, new IllegalStateException("Cannot get session state on a non-session receiver.")); } assert sessionManager != null; final String linkName = sessionManager.getLinkName(sessionId); return tracer.traceMono("ServiceBus.setSessionState", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.getSessionState(sessionId, linkName))) .onErrorMap((err) -> mapError(err, ServiceBusErrorSource.RECEIVE)); }
.flatMap(channel -> channel.getSessionState(sessionId, linkName)))
private Mono<byte[]> getSessionState(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState"))); } else if (!isSessionEnabled) { return monoError(LOGGER, new IllegalStateException("Cannot get session state on a non-session receiver.")); } assert sessionManager != null; final String linkName = sessionManager.getLinkName(sessionId); return tracer.traceMono("ServiceBus.setSessionState", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.getSessionState(sessionId, linkName))) .onErrorMap((err) -> mapError(err, ServiceBusErrorSource.RECEIVE)); }
class ServiceBusReceiverAsyncClient implements AutoCloseable { private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions(); private static final String TRANSACTION_LINK_NAME = "coordinator"; private static final ClientLogger LOGGER = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final LockContainer<LockRenewalOperation> renewalContainer; private final AtomicBoolean isDisposed = new AtomicBoolean(); private final LockContainer<OffsetDateTime> managementNodeLocks; private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final ReceiverOptions receiverOptions; private final ServiceBusConnectionProcessor connectionProcessor; private final ServiceBusReceiverInstrumentation instrumentation; private final ServiceBusTracer tracer; private final MessageSerializer messageSerializer; private final Runnable onClientClose; private final ServiceBusSessionManager sessionManager; private final boolean isSessionEnabled; private final Semaphore completionLock = new Semaphore(1); private final String identifier; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1); private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>(); private final AutoCloseable trackSettlementSequenceNumber; /** * Creates a receiver that listens to a Service Bus resource. * * @param fullyQualifiedNamespace The fully qualified domain name for the Service Bus resource. * @param entityPath The name of the topic or queue. * @param entityType The type of the Service Bus resource. * @param receiverOptions Options when receiving messages. * @param connectionProcessor The AMQP connection to the Service Bus resource. * @param instrumentation ServiceBus tracing and metrics helper * @param messageSerializer Serializes and deserializes Service Bus messages. * @param onClientClose Operation to run when the client completes. */ ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval, ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose, String identifier) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null"); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.sessionManager = null; if (receiverOptions.getSessionId() != null || receiverOptions.getMaxConcurrentSessions() != null) { throw new IllegalStateException("Session-specific options are not expected to be present on a client for session unaware entity."); } this.isSessionEnabled = false; this.managementNodeLocks = new LockContainer<>(cleanupInterval); this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, renewal.getLockToken()) .addKeyValue("status", renewal.getStatus()) .log("Closing expired renewal operation.", renewal.getThrowable()); renewal.close(); }); this.identifier = identifier; this.tracer = instrumentation.getTracer(); this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber(); } ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval, ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose, ServiceBusSessionManager sessionManager) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null"); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.sessionManager = Objects.requireNonNull(sessionManager, "'sessionManager' cannot be null."); this.isSessionEnabled = true; this.managementNodeLocks = new LockContainer<>(cleanupInterval); this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> { LOGGER.atInfo() .addKeyValue(SESSION_ID_KEY, renewal.getSessionId()) .addKeyValue("status", renewal.getStatus()) .log("Closing expired renewal operation.", renewal.getThrowable()); renewal.close(); }); this.identifier = sessionManager.getIdentifier(); this.tracer = instrumentation.getTracer(); this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber(); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return entityPath; } /** * Gets the SessionId of the session if this receiver is a session receiver. * * @return The SessionId or null if this is not a session receiver. */ public String getSessionId() { return receiverOptions.getSessionId(); } /** * Gets the identifier of the instance of {@link ServiceBusReceiverAsyncClient}. * * @return The identifier that can identify the instance of {@link ServiceBusReceiverAsyncClient}. */ public String getIdentifier() { return identifier; } /** * Abandons a {@link ServiceBusReceivedMessage message}. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the Service Bus abandon operation completes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.ABANDONED, null, null, null, null); } /** * Abandons a {@link ServiceBusReceivedMessage message} updates the message's properties. This will make the * message available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options The options to set while abandoning the message. * * @return A {@link Mono} that completes when the Service Bus operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, AbandonOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'settlementOptions' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.ABANDONED, null, null, options.getPropertiesToModify(), options.getTransactionContext()); } /** * Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that finishes when the message is completed on Service Bus. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be completed. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> complete(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null, null); } /** * Completes a {@link ServiceBusReceivedMessage message} with the given options. This will delete the message from * the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to complete the message. * * @return A {@link Mono} that finishes when the message is completed on Service Bus. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be completed. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> complete(ServiceBusReceivedMessage message, CompleteOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null, options.getTransactionContext()); } /** * Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the Service Bus defer operation finishes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @see <a href="https: */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.DEFERRED, null, null, null, null); } /** * Defers a {@link ServiceBusReceivedMessage message} with the options set. This will move message into * the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to defer the message. * * @return A {@link Mono} that completes when the defer operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @see <a href="https: */ public Mono<Void> defer(ServiceBusReceivedMessage message, DeferOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.DEFERRED, null, null, options.getPropertiesToModify(), options.getTransactionContext()); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the dead letter operation finishes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue with the given options. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to dead-letter the message. * * @return A {@link Mono} that completes when the dead letter operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.SUSPENDED, options.getDeadLetterReason(), options.getDeadLetterErrorDescription(), options.getPropertiesToModify(), options.getTransactionContext()); } /** * Gets the state of the session if this receiver is a session receiver. * * @return The session state or an empty Mono if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already closed. * @throws ServiceBusException if the session state could not be acquired. */ public Mono<byte[]> getSessionState() { return getSessionState(receiverOptions.getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ public Mono<ServiceBusReceivedMessage> peekMessage() { return peekMessage(receiverOptions.getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if the receiver is disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek"))); } Mono<ServiceBusReceivedMessage> result = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> { final long sequence = lastPeekedSequenceNumber.get() + 1; LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, sequence) .log("Peek message."); return channel.peek(sequence, sessionId, getLinkName(sessionId)); }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)) .handle((message, sink) -> { final long current = lastPeekedSequenceNumber .updateAndGet(value -> Math.max(value, message.getSequenceNumber())); LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, current) .log("Updating last peeked sequence number."); sink.next(message); }); return tracer.traceManagementReceive("ServiceBus.peekMessage", result); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ public Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber) { return peekMessage(sequenceNumber, receiverOptions.getSessionId()); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber, String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt"))); } return tracer.traceManagementReceive("ServiceBus.peekMessage", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE))); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} that are peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) { return tracer.traceSyncReceive("ServiceBus.peekMessages", peekMessages(maxMessages, receiverOptions.getSessionId())); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch"))); } if (maxMessages <= 0) { return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> { final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1; LOGGER.atVerbose().addKeyValue(SEQUENCE_NUMBER_KEY, nextSequenceNumber).log("Peek batch."); return node .peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages) .doOnNext(next -> { final long current = lastPeekedSequenceNumber .updateAndGet(value -> Math.max(value, next.getSequenceNumber())); LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, current) .log("Last peeked sequence number in batch."); }); }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber) { return peekMessages(maxMessages, sequenceNumber, receiverOptions.getSessionId()); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt"))); } if (maxMessages <= 0) { return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive.")); } return tracer.traceSyncReceive("ServiceBus.peekMessages", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages)) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE))); } /** * Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * This Flux continuously receives messages from a Service Bus entity until either: * * <ul> * <li>The receiver is closed.</li> * <li>The subscription to the Flux is disposed.</li> * <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux * {@link Flux * <li>An {@link AmqpException} occurs that causes the receive link to stop.</li> * </ul> * * <p> * The client uses an AMQP link underneath to receive the messages; the client will transparently transition to * a new AMQP link if the current one encounters a retriable error. When the client experiences a non-retriable error * or exhausts the retries, the Subscriber's {@link org.reactivestreams.Subscriber * will be notified with this error. No further messages will be delivered to {@link org.reactivestreams.Subscriber * after the terminal event; the application must create a new client to resume the receive. Re-subscribing to the Flux * of the old client will have no effect. * <br/> * Note: A few examples of non-retriable errors are - the application attempting to connect to a queue that does not * exist, deleting or disabling the queue in the middle of receiving, the user explicitly initiating Geo-DR. * These are certain events where the Service Bus communicates to the client that a non-retriable error occurred. * </p> * * @return An <b>infinite</b> stream of messages from the Service Bus entity. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while receiving messages. */ public Flux<ServiceBusReceivedMessage> receiveMessages() { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveMessages"))); } return receiveMessagesNoBackPressure().limitRate(1, 0); } @SuppressWarnings("try") Flux<ServiceBusReceivedMessage> receiveMessagesNoBackPressure() { return receiveMessagesWithContext(0) .handle((serviceBusMessageContext, sink) -> { if (serviceBusMessageContext.hasError()) { sink.error(serviceBusMessageContext.getThrowable()); return; } sink.next(serviceBusMessageContext.getMessage()); }); } /** * Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * This Flux continuously receives messages from a Service Bus entity until either: * * <ul> * <li>The receiver is closed.</li> * <li>The subscription to the Flux is disposed.</li> * <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux * {@link Flux * <li>An {@link AmqpException} occurs that causes the receive link to stop.</li> * </ul> * * @return An <b>infinite</b> stream of messages from the Service Bus entity. */ Flux<ServiceBusMessageContext> receiveMessagesWithContext() { return receiveMessagesWithContext(1); } Flux<ServiceBusMessageContext> receiveMessagesWithContext(int highTide) { final Flux<ServiceBusMessageContext> messageFlux = sessionManager != null ? sessionManager.receive() : getOrCreateConsumer().receive().map(ServiceBusMessageContext::new); final Flux<ServiceBusMessageContext> messageFluxWithTracing = new FluxTrace(messageFlux, instrumentation); final Flux<ServiceBusMessageContext> withAutoLockRenewal; if (!isSessionEnabled && receiverOptions.isAutoLockRenewEnabled()) { withAutoLockRenewal = new FluxAutoLockRenew(messageFluxWithTracing, receiverOptions, renewalContainer, this::renewMessageLock, tracer); } else { withAutoLockRenewal = messageFluxWithTracing; } Flux<ServiceBusMessageContext> result; if (receiverOptions.isEnableAutoComplete()) { result = new FluxAutoComplete(withAutoLockRenewal, completionLock, context -> context.getMessage() != null ? complete(context.getMessage()) : Mono.empty(), context -> context.getMessage() != null ? abandon(context.getMessage()) : Mono.empty()); } else { result = withAutoLockRenewal; } if (highTide > 0) { result = result.limitRate(highTide, 0); } return result .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return receiveDeferredMessage(sequenceNumber, receiverOptions.getSessionId()); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. {@code null} if there is no session. * * @return A deferred message with the matching {@code sequenceNumber}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessage"))); } return tracer.traceManagementReceive("ServiceBus.receiveDeferredMessage", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(), sessionId, getLinkName(sessionId), Collections.singleton(sequenceNumber)).last()) .map(receivedMessage -> { if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) { return receivedMessage; } if (receiverOptions.getReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(), receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil())); } return receivedMessage; }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE))); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return A {@link Flux} of deferred {@link ServiceBusReceivedMessage messages}. * * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred messages cannot be received. */ public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) { return tracer.traceSyncReceive("ServiceBus.receiveDeferredMessages", receiveDeferredMessages(sequenceNumbers, receiverOptions.getSessionId())); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. * @throws IllegalStateException if receiver is already disposed. * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws ServiceBusException if deferred message cannot be received. */ Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch"))); } if (sequenceNumbers == null) { return fluxError(LOGGER, new NullPointerException("'sequenceNumbers' cannot be null")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(), sessionId, getLinkName(sessionId), sequenceNumbers)) .map(receivedMessage -> { if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) { return receivedMessage; } if (receiverOptions.getReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(), receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil())); } return receivedMessage; }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Package-private method that releases a message. * * @param message Message to release. * @return Mono that completes when message is successfully released. */ Mono<Void> release(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.RELEASED, null, null, null, null); } /** * Asynchronously renews the lock on the message. The lock will be renewed based on the setting specified on the * entity. When a message is received in {@link ServiceBusReceiveMode * server for this receiver instance for a duration as specified during the entity creation (LockDuration). If * processing of the message requires longer than this duration, the lock needs to be renewed. For each renewal, the * lock is reset to the entity's LockDuration value. * * @param message The {@link ServiceBusReceivedMessage} to perform auto-lock renewal. * * @return The new expiration time for the message. * * @throws NullPointerException if {@code message} or {@code message.getLockToken()} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * @throws IllegalStateException if the receiver is a session receiver or receiver is already disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. */ public Mono<OffsetDateTime> renewMessageLock(ServiceBusReceivedMessage message) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } else if (isSessionEnabled) { final String errorMessage = "Renewing message lock is an invalid operation when working with sessions."; return monoError(LOGGER, new IllegalStateException(errorMessage)); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } else if (Objects.isNull(message.getLockToken())) { return monoError(LOGGER, new NullPointerException("'message.getLockToken()' cannot be null.")); } else if (message.getLockToken().isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } return tracer.traceRenewMessageLock(renewMessageLock(message.getLockToken()), message) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } /** * Asynchronously renews the lock on the message. The lock will be renewed based on the setting specified on the * entity. * * @param lockToken to be renewed. * * @return The new expiration time for the message. * @throws IllegalStateException if receiver is already disposed. */ Mono<OffsetDateTime> renewMessageLock(String lockToken) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode.renewMessageLock(lockToken, getLinkName(null))) .map(offsetDateTime -> managementNodeLocks.addOrUpdate(lockToken, offsetDateTime, offsetDateTime)); } /** * Starts the auto lock renewal for a {@link ServiceBusReceivedMessage message}. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param maxLockRenewalDuration Maximum duration to keep renewing the lock token. * * @return A Mono that completes when the message renewal operation has completed up until * {@code maxLockRenewalDuration}. * * @throws NullPointerException if {@code message}, {@code message.getLockToken()}, or * {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a session receiver or the receiver is disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. * @throws ServiceBusException If the message lock cannot be renewed. */ public Mono<Void> renewMessageLock(ServiceBusReceivedMessage message, Duration maxLockRenewalDuration) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock"))); } else if (isSessionEnabled) { final String errorMessage = "Renewing message lock is an invalid operation when working with sessions."; return monoError(LOGGER, new IllegalStateException(errorMessage)); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } else if (Objects.isNull(message.getLockToken())) { return monoError(LOGGER, new NullPointerException("'message.getLockToken()' cannot be null.")); } else if (message.getLockToken().isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } else if (maxLockRenewalDuration == null) { return monoError(LOGGER, new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { return monoError(LOGGER, new IllegalArgumentException("'maxLockRenewalDuration' cannot be negative.")); } final LockRenewalOperation operation = new LockRenewalOperation(message.getLockToken(), maxLockRenewalDuration, false, ignored -> renewMessageLock(message)); renewalContainer.addOrUpdate(message.getLockToken(), OffsetDateTime.now().plus(maxLockRenewalDuration), operation); return operation.getCompletionOperation() .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } /** * Renews the session lock if this receiver is a session receiver. * * @return The next expiration time for the session lock. * @throws IllegalStateException if the receiver is a non-session receiver or if receiver is already disposed. * @throws ServiceBusException if the session lock cannot be renewed. */ public Mono<OffsetDateTime> renewSessionLock() { return renewSessionLock(receiverOptions.getSessionId()); } /** * Starts the auto lock renewal for the session this receiver works for. * * @param maxLockRenewalDuration Maximum duration to keep renewing the session lock. * * @return A lock renewal operation for the message. * * @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed. * @throws ServiceBusException if the session lock renewal operation cannot be started. * @throws IllegalArgumentException if {@code sessionId} is an empty string or {@code maxLockRenewalDuration} is negative. */ public Mono<Void> renewSessionLock(Duration maxLockRenewalDuration) { return this.renewSessionLock(receiverOptions.getSessionId(), maxLockRenewalDuration); } /** * Sets the state of the session this receiver works for. * * @param sessionState State to set on the session. * * @return A Mono that completes when the session is set * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already disposed. * @throws ServiceBusException if the session state cannot be set. */ public Mono<Void> setSessionState(byte[] sessionState) { return this.setSessionState(receiverOptions.getSessionId(), sessionState); } /** * Starts a new service side transaction. The {@link ServiceBusTransactionContext transaction context} should be * passed to all operations that needs to be in this transaction. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @return The {@link Mono} that finishes this operation on service bus resource. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if a transaction cannot be created. */ public Mono<ServiceBusTransactionContext> createTransaction() { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction"))); } return tracer.traceMono("ServiceBus.commitTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(AmqpSession::createTransaction) .map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Commits the transaction and all the operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @param transactionContext The transaction to be commit. * * @return The {@link Mono} that finishes this operation on service bus resource. * * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the transaction could not be committed. */ public Mono<Void> commitTransaction(ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "commitTransaction"))); } if (Objects.isNull(transactionContext)) { return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null.")); } else if (Objects.isNull(transactionContext.getTransactionId())) { return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null.")); } return tracer.traceMono("ServiceBus.commitTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction( transactionContext.getTransactionId())))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Rollbacks the transaction given and all operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @param transactionContext The transaction to rollback. * * @return The {@link Mono} that finishes this operation on service bus resource. * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the transaction could not be rolled back. */ public Mono<Void> rollbackTransaction(ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "rollbackTransaction"))); } if (Objects.isNull(transactionContext)) { return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null.")); } else if (Objects.isNull(transactionContext.getTransactionId())) { return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null.")); } return tracer.traceMono("ServiceBus.rollbackTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction( transactionContext.getTransactionId())))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Disposes of the consumer by closing the underlying links to the service. */ @Override public void close() { if (isDisposed.get()) { return; } try { boolean acquired = completionLock.tryAcquire(5, TimeUnit.SECONDS); if (!acquired) { LOGGER.info("Unable to obtain completion lock."); } } catch (InterruptedException e) { LOGGER.info("Unable to obtain completion lock.", e); } if (isDisposed.getAndSet(true)) { return; } LOGGER.info("Removing receiver links."); final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null); if (disposed != null) { disposed.close(); } if (sessionManager != null) { sessionManager.close(); } managementNodeLocks.close(); renewalContainer.close(); if (trackSettlementSequenceNumber != null) { try { trackSettlementSequenceNumber.close(); } catch (Exception e) { LOGGER.info("Unable to close settlement sequence number subscription.", e); } } onClientClose.run(); } /** * @return receiver options set by user; */ ReceiverOptions getReceiverOptions() { return receiverOptions; } /** * Gets whether or not the management node contains the message lock token and it has not expired. Lock tokens are * held by the management node when they are received from the management node or management operations are * performed using that {@code lockToken}. * * @param lockToken Lock token to check for. * * @return {@code true} if the management node contains the lock token and false otherwise. */ private boolean isManagementToken(String lockToken) { return managementNodeLocks.containsUnexpired(lockToken); } private Mono<Void> updateDisposition(ServiceBusReceivedMessage message, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, dispositionStatus.getValue()))); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } final String lockToken = message.getLockToken(); final String sessionId = message.getSessionId(); if (receiverOptions.getReceiveMode() != ServiceBusReceiveMode.PEEK_LOCK) { return Mono.error(LOGGER.logExceptionAsError(new UnsupportedOperationException(String.format( "'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus)))); } else if (message.isSettled()) { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("The message has either been deleted or already settled."))); } else if (message.getLockToken() == null) { final String errorMessage = "This operation is not supported for peeked messages. " + "Only messages received using receiveMessages() in PEEK_LOCK mode can be settled."; return Mono.error( LOGGER.logExceptionAsError(new UnsupportedOperationException(errorMessage)) ); } final String sessionIdToUse; if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) { sessionIdToUse = receiverOptions.getSessionId(); } else { sessionIdToUse = sessionId; } LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(SESSION_ID_KEY, sessionIdToUse) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Update started."); final Mono<Void> performOnManagement = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, sessionId, getLinkName(sessionId), transactionContext)) .then(Mono.fromRunnable(() -> { LOGGER.atInfo() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Management node Update completed."); message.setIsSettled(); managementNodeLocks.remove(lockToken); renewalContainer.remove(lockToken); })); Mono<Void> updateDispositionOperation; if (sessionManager != null) { updateDispositionOperation = sessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify, deadLetterReason, deadLetterErrorDescription, transactionContext) .flatMap(isSuccess -> { if (isSuccess) { message.setIsSettled(); renewalContainer.remove(lockToken); return Mono.empty(); } LOGGER.info("Could not perform on session manger. Performing on management node."); return performOnManagement; }); } else { final ServiceBusAsyncConsumer existingConsumer = consumer.get(); if (isManagementToken(lockToken) || existingConsumer == null) { updateDispositionOperation = performOnManagement; } else { updateDispositionOperation = existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext) .then(Mono.fromRunnable(() -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Update completed."); message.setIsSettled(); renewalContainer.remove(lockToken); })); } } return instrumentation.instrumentSettlement(updateDispositionOperation, message, message.getContext(), dispositionStatus) .onErrorMap(throwable -> { if (throwable instanceof ServiceBusException) { return throwable; } switch (dispositionStatus) { case COMPLETED: return new ServiceBusException(throwable, ServiceBusErrorSource.COMPLETE); case ABANDONED: return new ServiceBusException(throwable, ServiceBusErrorSource.ABANDON); default: return new ServiceBusException(throwable, ServiceBusErrorSource.UNKNOWN); } }); } private ServiceBusAsyncConsumer getOrCreateConsumer() { if (isSessionEnabled) { throw LOGGER.logExceptionAsError(new IllegalStateException("The ServiceBusAsyncConsumer is expected to work only with session unaware entity.")); } final ServiceBusAsyncConsumer existing = consumer.get(); if (existing != null) { return existing; } final String linkName = StringUtil.getRandomString(entityPath); LOGGER.atInfo() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, entityPath) .log("Creating consumer."); final Mono<ServiceBusReceiveLink> receiveLinkMono = connectionProcessor.flatMap(connection -> { return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(), null, entityType, identifier); }).doOnNext(next -> { LOGGER.atVerbose() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, next.getEntityPath()) .addKeyValue("mode", receiverOptions.getReceiveMode()) .addKeyValue("isSessionEnabled", false) .addKeyValue(ENTITY_TYPE_KEY, entityType) .log("Created consumer for Service Bus resource."); }); final Mono<ServiceBusReceiveLink> retryableReceiveLinkMono = RetryUtil.withRetry(receiveLinkMono.onErrorMap( RequestResponseChannelClosedException.class, e -> { return new AmqpException(true, e.getMessage(), e, null); }), connectionProcessor.getRetryOptions(), "Failed to create receive link " + linkName, true); final Flux<ServiceBusReceiveLink> receiveLinkFlux = retryableReceiveLinkMono .repeat() .filter(link -> !link.isDisposed()); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLinkFlux.subscribeWith( new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy)); final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor, messageSerializer, receiverOptions); if (consumer.compareAndSet(null, newConsumer)) { return newConsumer; } else { newConsumer.close(); return consumer.get(); } } /** * If the receiver has not connected via {@link * through the management node. * * @return The name of the receive link, or null of it has not connected via a receive link. */ private String getLinkName(String sessionId) { if (!CoreUtils.isNullOrEmpty(sessionId)) { return isSessionEnabled ? sessionManager.getLinkName(sessionId) : null; } else { final ServiceBusAsyncConsumer existing = consumer.get(); return existing != null ? existing.getLinkName() : null; } } private Mono<OffsetDateTime> renewSessionLock(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock"))); } else if (!isSessionEnabled) { return monoError(LOGGER, new IllegalStateException("Cannot renew session lock on a non-session receiver.")); } final String linkName = sessionManager.getLinkName(sessionId); return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> tracer.traceMono("ServiceBus.renewSessionLock", channel.renewSessionLock(sessionId, linkName))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } private Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock"))); } else if (!isSessionEnabled) { return monoError(LOGGER, new IllegalStateException( "Cannot renew session lock on a non-session receiver.")); } else if (maxLockRenewalDuration == null) { return monoError(LOGGER, new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { return monoError(LOGGER, new IllegalArgumentException( "'maxLockRenewalDuration' cannot be negative.")); } else if (Objects.isNull(sessionId)) { return monoError(LOGGER, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'sessionId' cannot be empty.")); } final LockRenewalOperation operation = new LockRenewalOperation(sessionId, maxLockRenewalDuration, true, this::renewSessionLock); renewalContainer.addOrUpdate(sessionId, OffsetDateTime.now().plus(maxLockRenewalDuration), operation); return operation.getCompletionOperation(); } private Mono<Void> setSessionState(String sessionId, byte[] sessionState) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState"))); } else if (!isSessionEnabled) { return monoError(LOGGER, new IllegalStateException("Cannot set session state on a non-session receiver.")); } assert sessionManager != null; final String linkName = sessionManager.getLinkName(sessionId); return tracer.traceMono("ServiceBus.setSessionState", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName))) .onErrorMap((err) -> mapError(err, ServiceBusErrorSource.RECEIVE)); } ServiceBusReceiverInstrumentation getInstrumentation() { return instrumentation; } /** * Map the error to {@link ServiceBusException} */ private Throwable mapError(Throwable throwable, ServiceBusErrorSource errorSource) { if (!(throwable instanceof ServiceBusException)) { return new ServiceBusException(throwable, errorSource); } return throwable; } boolean isConnectionClosed() { return this.connectionProcessor.isChannelClosed(); } boolean isManagementNodeLocksClosed() { return this.managementNodeLocks.isClosed(); } boolean isRenewalContainerClosed() { return this.renewalContainer.isClosed(); } }
class ServiceBusReceiverAsyncClient implements AutoCloseable { private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions(); private static final String TRANSACTION_LINK_NAME = "coordinator"; private static final ClientLogger LOGGER = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final LockContainer<LockRenewalOperation> renewalContainer; private final AtomicBoolean isDisposed = new AtomicBoolean(); private final LockContainer<OffsetDateTime> managementNodeLocks; private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final ReceiverOptions receiverOptions; private final ServiceBusConnectionProcessor connectionProcessor; private final ServiceBusReceiverInstrumentation instrumentation; private final ServiceBusTracer tracer; private final MessageSerializer messageSerializer; private final Runnable onClientClose; private final ServiceBusSessionManager sessionManager; private final boolean isSessionEnabled; private final Semaphore completionLock = new Semaphore(1); private final String identifier; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1); private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>(); private final AutoCloseable trackSettlementSequenceNumber; /** * Creates a receiver that listens to a Service Bus resource. * * @param fullyQualifiedNamespace The fully qualified domain name for the Service Bus resource. * @param entityPath The name of the topic or queue. * @param entityType The type of the Service Bus resource. * @param receiverOptions Options when receiving messages. * @param connectionProcessor The AMQP connection to the Service Bus resource. * @param instrumentation ServiceBus tracing and metrics helper * @param messageSerializer Serializes and deserializes Service Bus messages. * @param onClientClose Operation to run when the client completes. */ ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval, ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose, String identifier) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null"); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.sessionManager = null; if (receiverOptions.getSessionId() != null || receiverOptions.getMaxConcurrentSessions() != null) { throw new IllegalStateException("Session-specific options are not expected to be present on a client for session unaware entity."); } this.isSessionEnabled = false; this.managementNodeLocks = new LockContainer<>(cleanupInterval); this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, renewal.getLockToken()) .addKeyValue("status", renewal.getStatus()) .log("Closing expired renewal operation.", renewal.getThrowable()); renewal.close(); }); this.identifier = identifier; this.tracer = instrumentation.getTracer(); this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber(); } ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval, ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose, ServiceBusSessionManager sessionManager) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null"); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.sessionManager = Objects.requireNonNull(sessionManager, "'sessionManager' cannot be null."); this.isSessionEnabled = true; this.managementNodeLocks = new LockContainer<>(cleanupInterval); this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> { LOGGER.atInfo() .addKeyValue(SESSION_ID_KEY, renewal.getSessionId()) .addKeyValue("status", renewal.getStatus()) .log("Closing expired renewal operation.", renewal.getThrowable()); renewal.close(); }); this.identifier = sessionManager.getIdentifier(); this.tracer = instrumentation.getTracer(); this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber(); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return entityPath; } /** * Gets the SessionId of the session if this receiver is a session receiver. * * @return The SessionId or null if this is not a session receiver. */ public String getSessionId() { return receiverOptions.getSessionId(); } /** * Gets the identifier of the instance of {@link ServiceBusReceiverAsyncClient}. * * @return The identifier that can identify the instance of {@link ServiceBusReceiverAsyncClient}. */ public String getIdentifier() { return identifier; } /** * Abandons a {@link ServiceBusReceivedMessage message}. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the Service Bus abandon operation completes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.ABANDONED, null, null, null, null); } /** * Abandons a {@link ServiceBusReceivedMessage message} updates the message's properties. This will make the * message available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options The options to set while abandoning the message. * * @return A {@link Mono} that completes when the Service Bus operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, AbandonOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'settlementOptions' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.ABANDONED, null, null, options.getPropertiesToModify(), options.getTransactionContext()); } /** * Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that finishes when the message is completed on Service Bus. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be completed. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> complete(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null, null); } /** * Completes a {@link ServiceBusReceivedMessage message} with the given options. This will delete the message from * the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to complete the message. * * @return A {@link Mono} that finishes when the message is completed on Service Bus. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be completed. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> complete(ServiceBusReceivedMessage message, CompleteOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null, options.getTransactionContext()); } /** * Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the Service Bus defer operation finishes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @see <a href="https: */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.DEFERRED, null, null, null, null); } /** * Defers a {@link ServiceBusReceivedMessage message} with the options set. This will move message into * the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to defer the message. * * @return A {@link Mono} that completes when the defer operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @see <a href="https: */ public Mono<Void> defer(ServiceBusReceivedMessage message, DeferOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.DEFERRED, null, null, options.getPropertiesToModify(), options.getTransactionContext()); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the dead letter operation finishes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue with the given options. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to dead-letter the message. * * @return A {@link Mono} that completes when the dead letter operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.SUSPENDED, options.getDeadLetterReason(), options.getDeadLetterErrorDescription(), options.getPropertiesToModify(), options.getTransactionContext()); } /** * Gets the state of the session if this receiver is a session receiver. * * @return The session state or an empty Mono if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already closed. * @throws ServiceBusException if the session state could not be acquired. */ public Mono<byte[]> getSessionState() { return getSessionState(receiverOptions.getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ public Mono<ServiceBusReceivedMessage> peekMessage() { return peekMessage(receiverOptions.getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if the receiver is disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek"))); } Mono<ServiceBusReceivedMessage> result = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> { final long sequence = lastPeekedSequenceNumber.get() + 1; LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, sequence) .log("Peek message."); return channel.peek(sequence, sessionId, getLinkName(sessionId)); }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)) .handle((message, sink) -> { final long current = lastPeekedSequenceNumber .updateAndGet(value -> Math.max(value, message.getSequenceNumber())); LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, current) .log("Updating last peeked sequence number."); sink.next(message); }); return tracer.traceManagementReceive("ServiceBus.peekMessage", result); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ public Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber) { return peekMessage(sequenceNumber, receiverOptions.getSessionId()); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber, String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt"))); } return tracer.traceManagementReceive("ServiceBus.peekMessage", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE))); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} that are peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) { return tracer.traceSyncReceive("ServiceBus.peekMessages", peekMessages(maxMessages, receiverOptions.getSessionId())); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch"))); } if (maxMessages <= 0) { return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> { final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1; LOGGER.atVerbose().addKeyValue(SEQUENCE_NUMBER_KEY, nextSequenceNumber).log("Peek batch."); return node .peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages) .doOnNext(next -> { final long current = lastPeekedSequenceNumber .updateAndGet(value -> Math.max(value, next.getSequenceNumber())); LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, current) .log("Last peeked sequence number in batch."); }); }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber) { return peekMessages(maxMessages, sequenceNumber, receiverOptions.getSessionId()); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt"))); } if (maxMessages <= 0) { return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive.")); } return tracer.traceSyncReceive("ServiceBus.peekMessages", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages)) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE))); } /** * Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * This Flux continuously receives messages from a Service Bus entity until either: * * <ul> * <li>The receiver is closed.</li> * <li>The subscription to the Flux is disposed.</li> * <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux * {@link Flux * <li>An {@link AmqpException} occurs that causes the receive link to stop.</li> * </ul> * * <p> * The client uses an AMQP link underneath to receive the messages; the client will transparently transition to * a new AMQP link if the current one encounters a retriable error. When the client experiences a non-retriable error * or exhausts the retries, the Subscriber's {@link org.reactivestreams.Subscriber * will be notified with this error. No further messages will be delivered to {@link org.reactivestreams.Subscriber * after the terminal event; the application must create a new client to resume the receive. Re-subscribing to the Flux * of the old client will have no effect. * <br/> * Note: A few examples of non-retriable errors are - the application attempting to connect to a queue that does not * exist, deleting or disabling the queue in the middle of receiving, the user explicitly initiating Geo-DR. * These are certain events where the Service Bus communicates to the client that a non-retriable error occurred. * </p> * * @return An <b>infinite</b> stream of messages from the Service Bus entity. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while receiving messages. */ public Flux<ServiceBusReceivedMessage> receiveMessages() { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveMessages"))); } return receiveMessagesNoBackPressure().limitRate(1, 0); } @SuppressWarnings("try") Flux<ServiceBusReceivedMessage> receiveMessagesNoBackPressure() { return receiveMessagesWithContext(0) .handle((serviceBusMessageContext, sink) -> { if (serviceBusMessageContext.hasError()) { sink.error(serviceBusMessageContext.getThrowable()); return; } sink.next(serviceBusMessageContext.getMessage()); }); } /** * Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * This Flux continuously receives messages from a Service Bus entity until either: * * <ul> * <li>The receiver is closed.</li> * <li>The subscription to the Flux is disposed.</li> * <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux * {@link Flux * <li>An {@link AmqpException} occurs that causes the receive link to stop.</li> * </ul> * * @return An <b>infinite</b> stream of messages from the Service Bus entity. */ Flux<ServiceBusMessageContext> receiveMessagesWithContext() { return receiveMessagesWithContext(1); } Flux<ServiceBusMessageContext> receiveMessagesWithContext(int highTide) { final Flux<ServiceBusMessageContext> messageFlux = sessionManager != null ? sessionManager.receive() : getOrCreateConsumer().receive().map(ServiceBusMessageContext::new); final Flux<ServiceBusMessageContext> messageFluxWithTracing = new FluxTrace(messageFlux, instrumentation); final Flux<ServiceBusMessageContext> withAutoLockRenewal; if (!isSessionEnabled && receiverOptions.isAutoLockRenewEnabled()) { withAutoLockRenewal = new FluxAutoLockRenew(messageFluxWithTracing, receiverOptions, renewalContainer, this::renewMessageLock, tracer); } else { withAutoLockRenewal = messageFluxWithTracing; } Flux<ServiceBusMessageContext> result; if (receiverOptions.isEnableAutoComplete()) { result = new FluxAutoComplete(withAutoLockRenewal, completionLock, context -> context.getMessage() != null ? complete(context.getMessage()) : Mono.empty(), context -> context.getMessage() != null ? abandon(context.getMessage()) : Mono.empty()); } else { result = withAutoLockRenewal; } if (highTide > 0) { result = result.limitRate(highTide, 0); } return result .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return receiveDeferredMessage(sequenceNumber, receiverOptions.getSessionId()); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. {@code null} if there is no session. * * @return A deferred message with the matching {@code sequenceNumber}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessage"))); } return tracer.traceManagementReceive("ServiceBus.receiveDeferredMessage", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(), sessionId, getLinkName(sessionId), Collections.singleton(sequenceNumber)).last()) .map(receivedMessage -> { if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) { return receivedMessage; } if (receiverOptions.getReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(), receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil())); } return receivedMessage; }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE))); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return A {@link Flux} of deferred {@link ServiceBusReceivedMessage messages}. * * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred messages cannot be received. */ public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) { return tracer.traceSyncReceive("ServiceBus.receiveDeferredMessages", receiveDeferredMessages(sequenceNumbers, receiverOptions.getSessionId())); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. * @throws IllegalStateException if receiver is already disposed. * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws ServiceBusException if deferred message cannot be received. */ Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch"))); } if (sequenceNumbers == null) { return fluxError(LOGGER, new NullPointerException("'sequenceNumbers' cannot be null")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(), sessionId, getLinkName(sessionId), sequenceNumbers)) .map(receivedMessage -> { if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) { return receivedMessage; } if (receiverOptions.getReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(), receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil())); } return receivedMessage; }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Package-private method that releases a message. * * @param message Message to release. * @return Mono that completes when message is successfully released. */ Mono<Void> release(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.RELEASED, null, null, null, null); } /** * Asynchronously renews the lock on the message. The lock will be renewed based on the setting specified on the * entity. When a message is received in {@link ServiceBusReceiveMode * server for this receiver instance for a duration as specified during the entity creation (LockDuration). If * processing of the message requires longer than this duration, the lock needs to be renewed. For each renewal, the * lock is reset to the entity's LockDuration value. * * @param message The {@link ServiceBusReceivedMessage} to perform auto-lock renewal. * * @return The new expiration time for the message. * * @throws NullPointerException if {@code message} or {@code message.getLockToken()} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * @throws IllegalStateException if the receiver is a session receiver or receiver is already disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. */ public Mono<OffsetDateTime> renewMessageLock(ServiceBusReceivedMessage message) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } else if (isSessionEnabled) { final String errorMessage = "Renewing message lock is an invalid operation when working with sessions."; return monoError(LOGGER, new IllegalStateException(errorMessage)); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } else if (Objects.isNull(message.getLockToken())) { return monoError(LOGGER, new NullPointerException("'message.getLockToken()' cannot be null.")); } else if (message.getLockToken().isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } return tracer.traceRenewMessageLock(renewMessageLock(message.getLockToken()), message) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } /** * Asynchronously renews the lock on the message. The lock will be renewed based on the setting specified on the * entity. * * @param lockToken to be renewed. * * @return The new expiration time for the message. * @throws IllegalStateException if receiver is already disposed. */ Mono<OffsetDateTime> renewMessageLock(String lockToken) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode.renewMessageLock(lockToken, getLinkName(null))) .map(offsetDateTime -> managementNodeLocks.addOrUpdate(lockToken, offsetDateTime, offsetDateTime)); } /** * Starts the auto lock renewal for a {@link ServiceBusReceivedMessage message}. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param maxLockRenewalDuration Maximum duration to keep renewing the lock token. * * @return A Mono that completes when the message renewal operation has completed up until * {@code maxLockRenewalDuration}. * * @throws NullPointerException if {@code message}, {@code message.getLockToken()}, or * {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a session receiver or the receiver is disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. * @throws ServiceBusException If the message lock cannot be renewed. */ public Mono<Void> renewMessageLock(ServiceBusReceivedMessage message, Duration maxLockRenewalDuration) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock"))); } else if (isSessionEnabled) { final String errorMessage = "Renewing message lock is an invalid operation when working with sessions."; return monoError(LOGGER, new IllegalStateException(errorMessage)); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } else if (Objects.isNull(message.getLockToken())) { return monoError(LOGGER, new NullPointerException("'message.getLockToken()' cannot be null.")); } else if (message.getLockToken().isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } else if (maxLockRenewalDuration == null) { return monoError(LOGGER, new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { return monoError(LOGGER, new IllegalArgumentException("'maxLockRenewalDuration' cannot be negative.")); } final LockRenewalOperation operation = new LockRenewalOperation(message.getLockToken(), maxLockRenewalDuration, false, ignored -> renewMessageLock(message)); renewalContainer.addOrUpdate(message.getLockToken(), OffsetDateTime.now().plus(maxLockRenewalDuration), operation); return operation.getCompletionOperation() .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } /** * Renews the session lock if this receiver is a session receiver. * * @return The next expiration time for the session lock. * @throws IllegalStateException if the receiver is a non-session receiver or if receiver is already disposed. * @throws ServiceBusException if the session lock cannot be renewed. */ public Mono<OffsetDateTime> renewSessionLock() { return renewSessionLock(receiverOptions.getSessionId()); } /** * Starts the auto lock renewal for the session this receiver works for. * * @param maxLockRenewalDuration Maximum duration to keep renewing the session lock. * * @return A lock renewal operation for the message. * * @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed. * @throws ServiceBusException if the session lock renewal operation cannot be started. * @throws IllegalArgumentException if {@code sessionId} is an empty string or {@code maxLockRenewalDuration} is negative. */ public Mono<Void> renewSessionLock(Duration maxLockRenewalDuration) { return this.renewSessionLock(receiverOptions.getSessionId(), maxLockRenewalDuration); } /** * Sets the state of the session this receiver works for. * * @param sessionState State to set on the session. * * @return A Mono that completes when the session is set * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already disposed. * @throws ServiceBusException if the session state cannot be set. */ public Mono<Void> setSessionState(byte[] sessionState) { return this.setSessionState(receiverOptions.getSessionId(), sessionState); } /** * Starts a new service side transaction. The {@link ServiceBusTransactionContext transaction context} should be * passed to all operations that needs to be in this transaction. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @return The {@link Mono} that finishes this operation on service bus resource. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if a transaction cannot be created. */ public Mono<ServiceBusTransactionContext> createTransaction() { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction"))); } return tracer.traceMono("ServiceBus.commitTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(AmqpSession::createTransaction) .map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Commits the transaction and all the operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @param transactionContext The transaction to be commit. * * @return The {@link Mono} that finishes this operation on service bus resource. * * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the transaction could not be committed. */ public Mono<Void> commitTransaction(ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "commitTransaction"))); } if (Objects.isNull(transactionContext)) { return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null.")); } else if (Objects.isNull(transactionContext.getTransactionId())) { return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null.")); } return tracer.traceMono("ServiceBus.commitTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction( transactionContext.getTransactionId())))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Rollbacks the transaction given and all operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @param transactionContext The transaction to rollback. * * @return The {@link Mono} that finishes this operation on service bus resource. * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the transaction could not be rolled back. */ public Mono<Void> rollbackTransaction(ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "rollbackTransaction"))); } if (Objects.isNull(transactionContext)) { return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null.")); } else if (Objects.isNull(transactionContext.getTransactionId())) { return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null.")); } return tracer.traceMono("ServiceBus.rollbackTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction( transactionContext.getTransactionId())))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Disposes of the consumer by closing the underlying links to the service. */ @Override public void close() { if (isDisposed.get()) { return; } try { boolean acquired = completionLock.tryAcquire(5, TimeUnit.SECONDS); if (!acquired) { LOGGER.info("Unable to obtain completion lock."); } } catch (InterruptedException e) { LOGGER.info("Unable to obtain completion lock.", e); } if (isDisposed.getAndSet(true)) { return; } LOGGER.info("Removing receiver links."); final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null); if (disposed != null) { disposed.close(); } if (sessionManager != null) { sessionManager.close(); } managementNodeLocks.close(); renewalContainer.close(); if (trackSettlementSequenceNumber != null) { try { trackSettlementSequenceNumber.close(); } catch (Exception e) { LOGGER.info("Unable to close settlement sequence number subscription.", e); } } onClientClose.run(); } /** * @return receiver options set by user; */ ReceiverOptions getReceiverOptions() { return receiverOptions; } /** * Gets whether or not the management node contains the message lock token and it has not expired. Lock tokens are * held by the management node when they are received from the management node or management operations are * performed using that {@code lockToken}. * * @param lockToken Lock token to check for. * * @return {@code true} if the management node contains the lock token and false otherwise. */ private boolean isManagementToken(String lockToken) { return managementNodeLocks.containsUnexpired(lockToken); } private Mono<Void> updateDisposition(ServiceBusReceivedMessage message, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, dispositionStatus.getValue()))); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } final String lockToken = message.getLockToken(); final String sessionId = message.getSessionId(); if (receiverOptions.getReceiveMode() != ServiceBusReceiveMode.PEEK_LOCK) { return Mono.error(LOGGER.logExceptionAsError(new UnsupportedOperationException(String.format( "'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus)))); } else if (message.isSettled()) { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("The message has either been deleted or already settled."))); } else if (message.getLockToken() == null) { final String errorMessage = "This operation is not supported for peeked messages. " + "Only messages received using receiveMessages() in PEEK_LOCK mode can be settled."; return Mono.error( LOGGER.logExceptionAsError(new UnsupportedOperationException(errorMessage)) ); } final String sessionIdToUse; if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) { sessionIdToUse = receiverOptions.getSessionId(); } else { sessionIdToUse = sessionId; } LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(SESSION_ID_KEY, sessionIdToUse) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Update started."); final Mono<Void> performOnManagement = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, sessionId, getLinkName(sessionId), transactionContext)) .then(Mono.fromRunnable(() -> { LOGGER.atInfo() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Management node Update completed."); message.setIsSettled(); managementNodeLocks.remove(lockToken); renewalContainer.remove(lockToken); })); Mono<Void> updateDispositionOperation; if (sessionManager != null) { updateDispositionOperation = sessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify, deadLetterReason, deadLetterErrorDescription, transactionContext) .flatMap(isSuccess -> { if (isSuccess) { message.setIsSettled(); renewalContainer.remove(lockToken); return Mono.empty(); } LOGGER.info("Could not perform on session manger. Performing on management node."); return performOnManagement; }); } else { final ServiceBusAsyncConsumer existingConsumer = consumer.get(); if (isManagementToken(lockToken) || existingConsumer == null) { updateDispositionOperation = performOnManagement; } else { updateDispositionOperation = existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext) .then(Mono.fromRunnable(() -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Update completed."); message.setIsSettled(); renewalContainer.remove(lockToken); })); } } return instrumentation.instrumentSettlement(updateDispositionOperation, message, message.getContext(), dispositionStatus) .onErrorMap(throwable -> { if (throwable instanceof ServiceBusException) { return throwable; } switch (dispositionStatus) { case COMPLETED: return new ServiceBusException(throwable, ServiceBusErrorSource.COMPLETE); case ABANDONED: return new ServiceBusException(throwable, ServiceBusErrorSource.ABANDON); default: return new ServiceBusException(throwable, ServiceBusErrorSource.UNKNOWN); } }); } private ServiceBusAsyncConsumer getOrCreateConsumer() { if (isSessionEnabled) { throw LOGGER.logExceptionAsError(new IllegalStateException("The ServiceBusAsyncConsumer is expected to work only with session unaware entity.")); } final ServiceBusAsyncConsumer existing = consumer.get(); if (existing != null) { return existing; } final String linkName = StringUtil.getRandomString(entityPath); LOGGER.atInfo() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, entityPath) .log("Creating consumer."); final Mono<ServiceBusReceiveLink> receiveLinkMono = connectionProcessor.flatMap(connection -> { return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(), null, entityType, identifier); }).doOnNext(next -> { LOGGER.atVerbose() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, next.getEntityPath()) .addKeyValue("mode", receiverOptions.getReceiveMode()) .addKeyValue("isSessionEnabled", false) .addKeyValue(ENTITY_TYPE_KEY, entityType) .log("Created consumer for Service Bus resource."); }); final Mono<ServiceBusReceiveLink> retryableReceiveLinkMono = RetryUtil.withRetry(receiveLinkMono.onErrorMap( RequestResponseChannelClosedException.class, e -> { return new AmqpException(true, e.getMessage(), e, null); }), connectionProcessor.getRetryOptions(), "Failed to create receive link " + linkName, true); final Flux<ServiceBusReceiveLink> receiveLinkFlux = retryableReceiveLinkMono .repeat() .filter(link -> !link.isDisposed()); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLinkFlux.subscribeWith( new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy)); final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor, messageSerializer, receiverOptions); if (consumer.compareAndSet(null, newConsumer)) { return newConsumer; } else { newConsumer.close(); return consumer.get(); } } /** * If the receiver has not connected via {@link * through the management node. * * @return The name of the receive link, or null of it has not connected via a receive link. */ private String getLinkName(String sessionId) { if (!CoreUtils.isNullOrEmpty(sessionId)) { return isSessionEnabled ? sessionManager.getLinkName(sessionId) : null; } else { final ServiceBusAsyncConsumer existing = consumer.get(); return existing != null ? existing.getLinkName() : null; } } private Mono<OffsetDateTime> renewSessionLock(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock"))); } else if (!isSessionEnabled) { return monoError(LOGGER, new IllegalStateException("Cannot renew session lock on a non-session receiver.")); } final String linkName = sessionManager.getLinkName(sessionId); return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> tracer.traceMono("ServiceBus.renewSessionLock", channel.renewSessionLock(sessionId, linkName))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } private Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock"))); } else if (!isSessionEnabled) { return monoError(LOGGER, new IllegalStateException( "Cannot renew session lock on a non-session receiver.")); } else if (maxLockRenewalDuration == null) { return monoError(LOGGER, new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { return monoError(LOGGER, new IllegalArgumentException( "'maxLockRenewalDuration' cannot be negative.")); } else if (Objects.isNull(sessionId)) { return monoError(LOGGER, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'sessionId' cannot be empty.")); } final LockRenewalOperation operation = new LockRenewalOperation(sessionId, maxLockRenewalDuration, true, this::renewSessionLock); renewalContainer.addOrUpdate(sessionId, OffsetDateTime.now().plus(maxLockRenewalDuration), operation); return operation.getCompletionOperation(); } private Mono<Void> setSessionState(String sessionId, byte[] sessionState) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState"))); } else if (!isSessionEnabled) { return monoError(LOGGER, new IllegalStateException("Cannot set session state on a non-session receiver.")); } assert sessionManager != null; final String linkName = sessionManager.getLinkName(sessionId); return tracer.traceMono("ServiceBus.setSessionState", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName))) .onErrorMap((err) -> mapError(err, ServiceBusErrorSource.RECEIVE)); } ServiceBusReceiverInstrumentation getInstrumentation() { return instrumentation; } /** * Map the error to {@link ServiceBusException} */ private Throwable mapError(Throwable throwable, ServiceBusErrorSource errorSource) { if (!(throwable instanceof ServiceBusException)) { return new ServiceBusException(throwable, errorSource); } return throwable; } boolean isConnectionClosed() { return this.connectionProcessor.isChannelClosed(); } boolean isManagementNodeLocksClosed() { return this.managementNodeLocks.isClosed(); } boolean isRenewalContainerClosed() { return this.renewalContainer.isClosed(); } }
Removes the unnecessary internal method redirections; we can call the async methods directly ( + allows us to remove internal methods)
public OffsetDateTime renewSessionLock() { return asyncClient.renewSessionLock().block(operationTimeout); }
return asyncClient.renewSessionLock().block(operationTimeout);
public OffsetDateTime renewSessionLock() { return asyncClient.renewSessionLock().block(operationTimeout); }
class ServiceBusReceiverClient implements AutoCloseable { private static final ClientLogger LOGGER = new ClientLogger(ServiceBusReceiverClient.class); private final AtomicInteger idGenerator = new AtomicInteger(); private final ServiceBusReceiverAsyncClient asyncClient; private final Duration operationTimeout; private final boolean isPrefetchDisabled; /* To hold each receive work item to be processed.*/ private final AtomicReference<SynchronousMessageSubscriber> synchronousMessageSubscriber = new AtomicReference<>(); /* To ensure synchronousMessageSubscriber is subscribed only once. */ private final AtomicBoolean syncSubscribed = new AtomicBoolean(false); private final ServiceBusTracer tracer; /** * Creates a synchronous receiver given its asynchronous counterpart. * * @param asyncClient Asynchronous receiver. * @param isPrefetchDisabled Indicates if the prefetch is disabled. * @param operationTimeout Timeout to wait for operation to complete. */ ServiceBusReceiverClient(ServiceBusReceiverAsyncClient asyncClient, boolean isPrefetchDisabled, Duration operationTimeout) { this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); this.isPrefetchDisabled = isPrefetchDisabled; this.tracer = asyncClient.getInstrumentation().getTracer(); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return asyncClient.getFullyQualifiedNamespace(); } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return asyncClient.getEntityPath(); } /** * Gets the SessionId of the session if this receiver is a session receiver. * * @return The SessionId or null if this is not a session receiver. */ public String getSessionId() { return asyncClient.getSessionId(); } /** * Gets the identifier of the instance of {@link ServiceBusReceiverClient}. * * @return The identifier that can identify the instance of {@link ServiceBusReceiverClient}. */ public String getIdentifier() { return asyncClient.getIdentifier(); } /** * Abandons a {@link ServiceBusReceivedMessage message}. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public void abandon(ServiceBusReceivedMessage message) { asyncClient.abandon(message).block(operationTimeout); } /** * Abandons a {@link ServiceBusReceivedMessage message} and updates the message's properties. This will make the * message available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options The options to set while abandoning the message. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverClient * @throws IllegalStateException if receiver is already disposed. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @throws ServiceBusException if the message could not be abandoned. */ public void abandon(ServiceBusReceivedMessage message, AbandonOptions options) { asyncClient.abandon(message, options).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverClient * @throws IllegalStateException if receiver is already disposed. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @throws ServiceBusException if the message could not be completed. */ public void complete(ServiceBusReceivedMessage message) { asyncClient.complete(message).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to complete the message. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverClient * @throws IllegalStateException if receiver is already disposed. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @throws ServiceBusException if the message could not be completed. */ public void complete(ServiceBusReceivedMessage message, CompleteOptions options) { asyncClient.complete(message, options).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred subqueue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: */ public void defer(ServiceBusReceivedMessage message) { asyncClient.defer(message).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This * will move message into the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to defer the message. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: */ public void defer(ServiceBusReceivedMessage message, DeferOptions options) { asyncClient.defer(message, options).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public void deadLetter(ServiceBusReceivedMessage message) { asyncClient.deadLetter(message).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue with dead-letter reason, error * description, and/or modified properties. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to dead-letter the message. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverClient * @throws IllegalStateException if the receiver is already disposed of. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public void deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions options) { asyncClient.deadLetter(message, options).block(operationTimeout); } /** * Gets the state of the session if this receiver is a session receiver. * * @return The session state or null if there is no state set for the session. * * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already disposed. * @throws ServiceBusException if the session state could not be acquired. */ public byte[] getSessionState() { return asyncClient.getSessionState().block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peekMessage()} fetches the first active message for this receiver. Each subsequent call fetches the * subsequent message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * * @throws IllegalStateException if the receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * * @see <a href="https: */ public ServiceBusReceivedMessage peekMessage() { return this.peekMessage(asyncClient.getReceiverOptions().getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peekMessage()} fetches the first active message for this receiver. Each subsequent call fetches the * subsequent message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * * @throws IllegalStateException if receiver is already disposed or the receiver is a non-session receiver. * @throws ServiceBusException if an error occurs while peeking at the message. * * @see <a href="https: */ ServiceBusReceivedMessage peekMessage(String sessionId) { return asyncClient.peekMessage(sessionId).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * * @throws IllegalStateException if the receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * * @see <a href="https: */ public ServiceBusReceivedMessage peekMessage(long sequenceNumber) { return this.peekMessage(sequenceNumber, asyncClient.getReceiverOptions().getSessionId()); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * * @see <a href="https: */ ServiceBusReceivedMessage peekMessage(long sequenceNumber, String sessionId) { return asyncClient.peekMessage(sequenceNumber, sessionId).block(operationTimeout); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The maximum number of messages to peek. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if the receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekMessages(int maxMessages) { return this.peekMessages(maxMessages, asyncClient.getReceiverOptions().getSessionId()); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * * @see <a href="https: */ IterableStream<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) { if (maxMessages <= 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = tracer.traceSyncReceive("ServiceBus.peekMessages", asyncClient.peekMessages(maxMessages, sessionId).timeout(operationTimeout)); return fromFluxAndSubscribe(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if the receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber) { return this.peekMessages(maxMessages, sequenceNumber, asyncClient.getReceiverOptions().getSessionId()); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * * @see <a href="https: */ IterableStream<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber, String sessionId) { if (maxMessages <= 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = tracer.traceSyncReceive("ServiceBus.peekMessages", asyncClient.peekMessages(maxMessages, sequenceNumber, sessionId).timeout(operationTimeout)); return fromFluxAndSubscribe(messages); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. The * receive operation will wait for a default 1 minute for receiving a message before it times out. You can * override it by using {@link * * <p> * The client uses an AMQP link underneath to receive the messages; the client will transparently transition * to a new AMQP link if the current one encounters a retriable error. When the client experiences a non-retriable * error or exhausts the retries, the iteration (e.g., forEach) on the {@link IterableStream} returned by the further * invocations of receiveMessages API will throw the error to the application. Once the application receives * this error, the application should reset the client, i.e., close the current {@link ServiceBusReceiverClient} * and create a new client to continue receiving messages. * <br/> * Note: A few examples of non-retriable errors are - the application attempting to connect to a queue that does not * exist, deleting or disabling the queue in the middle of receiving, the user explicitly initiating Geo-DR. * These are certain events where the Service Bus communicates to the client that a non-retriable error occurred. * </p> * * @param maxMessages The maximum number of messages to receive. * * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} is zero or a negative value. * @throws IllegalStateException if the receiver is already disposed. * @throws ServiceBusException if an error occurs while receiving messages. * * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> receiveMessages(int maxMessages) { return receiveMessages(maxMessages, operationTimeout); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. The * default receive mode is {@link ServiceBusReceiveMode * ServiceBusReceiverClient} using {@link ServiceBusReceiverClientBuilder * * <p> * The client uses an AMQP link underneath to receive the messages; the client will transparently transition * to a new AMQP link if the current one encounters a retriable error. When the client experiences a non-retriable * error or exhausts the retries, the iteration (e.g., forEach) on the {@link IterableStream} returned by the further * invocations of receiveMessages API will throw the error to the application. Once the application receives * this error, the application should reset the client, i.e., close the current {@link ServiceBusReceiverClient} * and create a new client to continue receiving messages. * <br/> * Note: A few examples of non-retriable errors are - the application attempting to connect to a queue that does not * exist, deleting or disabling the queue in the middle of receiving, the user explicitly initiating Geo-DR. * These are certain events where the Service Bus communicates to the client that a non-retriable error occurred. * </p> * * @param maxMessages The maximum number of messages to receive. * @param maxWaitTime The time the client waits for receiving a message before it times out. * * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} or {@code maxWaitTime} is zero or a negative value. * @throws IllegalStateException if the receiver is already disposed. * @throws NullPointerException if {@code maxWaitTime} is null. * @throws ServiceBusException if an error occurs while receiving messages. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> receiveMessages(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw LOGGER.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } final Sinks.Many<ServiceBusReceivedMessage> emitter = Sinks.many().replay().all(); queueWork(maxMessages, maxWaitTime, emitter); final Flux<ServiceBusReceivedMessage> messagesFlux = tracer.traceSyncReceive("ServiceBus.receiveMessages", emitter.asFlux()); messagesFlux.subscribe(); return new IterableStream<>(messagesFlux); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber) { return this.receiveDeferredMessage(sequenceNumber, asyncClient.getReceiverOptions().getSessionId()); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. * * @return A deferred message with the matching {@code sequenceNumber}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber, String sessionId) { return asyncClient.receiveDeferredMessage(sequenceNumber, sessionId).block(operationTimeout); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. * * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred messages cannot be received. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers) { return this.receiveDeferredMessageBatch(sequenceNumbers, asyncClient.getReceiverOptions().getSessionId()); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. * * @throws IllegalStateException if receiver is already disposed. * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws ServiceBusException if deferred message cannot be received. */ IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers, String sessionId) { final Flux<ServiceBusReceivedMessage> messages = tracer.traceSyncReceive("ServiceBus.receiveDeferredMessageBatch", asyncClient.receiveDeferredMessages(sequenceNumbers, sessionId).timeout(operationTimeout)); return fromFluxAndSubscribe(messages); } /** * Renews the lock on the specified message. The lock will be renewed based on the setting specified on the entity. * When a message is received in {@link ServiceBusReceiveMode * server for this receiver instance for a duration as specified during the Queue creation (LockDuration). If * processing of the message requires longer than this duration, the lock needs to be renewed. For each renewal, * the lock is reset to the entity's LockDuration value. * * @param message The {@link ServiceBusReceivedMessage} to perform lock renewal. * * @return The new expiration time for the message. * * @throws NullPointerException if {@code message} or {@code message.getLockToken()} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * @throws IllegalStateException if the receiver is a session receiver or receiver is already disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. */ public OffsetDateTime renewMessageLock(ServiceBusReceivedMessage message) { return asyncClient.renewMessageLock(message).block(operationTimeout); } /** * Starts the auto lock renewal for a message with the given lock. * * @param message The {@link ServiceBusReceivedMessage} to perform auto-lock renewal. * @param maxLockRenewalDuration Maximum duration to keep renewing the lock token. * @param onError A function to call when an error occurs during lock renewal. * * @throws NullPointerException if {@code message}, {@code message.getLockToken()}, or * {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a session receiver or the receiver is disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. * @throws ServiceBusException If the message cannot be renewed. */ public void renewMessageLock(ServiceBusReceivedMessage message, Duration maxLockRenewalDuration, Consumer<Throwable> onError) { final String lockToken = message != null ? message.getLockToken() : "null"; final Consumer<Throwable> throwableConsumer = onError != null ? onError : error -> LOGGER.atWarning().addKeyValue(LOCK_TOKEN_KEY, lockToken).log("Exception occurred while renewing lock token.", error); asyncClient.renewMessageLock(message, maxLockRenewalDuration).subscribe( v -> LOGGER.atVerbose().addKeyValue(LOCK_TOKEN_KEY, lockToken).log("Completed renewing lock token."), throwableConsumer, () -> LOGGER.atVerbose().addKeyValue(LOCK_TOKEN_KEY, lockToken).log("Auto message lock renewal operation completed")); } /** * Sets the state of the session if this receiver is a session receiver. * * @return The next expiration time for the session lock. * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already disposed. * @throws ServiceBusException if the session lock cannot be renewed. */ /** * Starts the auto lock renewal for the session that this receiver works for. * * @param maxLockRenewalDuration Maximum duration to keep renewing the session. * @param onError A function to call when an error occurs during lock renewal. * * @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null. * @throws IllegalArgumentException if {@code sessionId} is an empty string or {@code maxLockRenewalDuration} is negative. * @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed. * @throws ServiceBusException if the session lock renewal operation cannot be started. */ public void renewSessionLock(Duration maxLockRenewalDuration, Consumer<Throwable> onError) { this.renewSessionLock(asyncClient.getReceiverOptions().getSessionId(), maxLockRenewalDuration, onError); } /** * Sets the state of the session if this receiver is a session receiver. * * @param sessionState State to set on the session. * * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already disposed. * @throws ServiceBusException if the session state cannot be set. */ public void setSessionState(byte[] sessionState) { asyncClient.setSessionState(sessionState).block(operationTimeout); } /** * Starts a new transaction on Service Bus. The {@link ServiceBusTransactionContext} should be passed along to all * operations that need to be in this transaction. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverclient.committransaction * <pre> * ServiceBusTransactionContext transaction = receiver.createTransaction& * * & * ServiceBusReceivedMessage deferredMessage = receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * receiver.commitTransaction& * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverclient.committransaction * * @return A new {@link ServiceBusTransactionContext}. * * @throws IllegalStateException if the receiver is already disposed. * @throws ServiceBusException if a transaction cannot be created. */ public ServiceBusTransactionContext createTransaction() { return asyncClient.createTransaction().block(operationTimeout); } /** * Commits the transaction and all the operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverclient.committransaction * <pre> * ServiceBusTransactionContext transaction = receiver.createTransaction& * * & * ServiceBusReceivedMessage deferredMessage = receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * receiver.commitTransaction& * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverclient.committransaction * * @param transactionContext The transaction to be commit. * * @throws IllegalStateException if the receiver is already disposed. * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws ServiceBusException if the transaction could not be committed. */ public void commitTransaction(ServiceBusTransactionContext transactionContext) { asyncClient.commitTransaction(transactionContext).block(operationTimeout); } /** * Rollbacks the transaction given and all operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverclient.committransaction * <pre> * ServiceBusTransactionContext transaction = receiver.createTransaction& * * & * ServiceBusReceivedMessage deferredMessage = receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * receiver.commitTransaction& * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverclient.committransaction * * @param transactionContext The transaction to be rollback. * * @throws IllegalStateException if the receiver is already disposed. * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws ServiceBusException if the transaction could not be rolled back. */ public void rollbackTransaction(ServiceBusTransactionContext transactionContext) { asyncClient.rollbackTransaction(transactionContext).block(operationTimeout); } /** * Disposes of the consumer by closing the underlying links to the service. */ @Override public void close() { SynchronousMessageSubscriber messageSubscriber = synchronousMessageSubscriber.get(); if (messageSubscriber != null && !messageSubscriber.isDisposed()) { messageSubscriber.dispose(); } asyncClient.close(); } /** * Given an {@code emitter}, creates a {@link SynchronousMessageSubscriber} to receive messages from Service Bus * entity. */ private void queueWork(int maximumMessageCount, Duration maxWaitTime, Sinks.Many<ServiceBusReceivedMessage> emitter) { final long id = idGenerator.getAndIncrement(); final SynchronousReceiveWork work = new SynchronousReceiveWork(id, maximumMessageCount, maxWaitTime, emitter); SynchronousMessageSubscriber messageSubscriber = synchronousMessageSubscriber.get(); if (messageSubscriber != null) { messageSubscriber.queueWork(work); return; } messageSubscriber = synchronousMessageSubscriber.updateAndGet(subscriber -> { if (subscriber == null) { return new SynchronousMessageSubscriber(asyncClient, work, isPrefetchDisabled, operationTimeout); } else { return subscriber; } }); if (!syncSubscribed.getAndSet(true)) { asyncClient.receiveMessagesNoBackPressure().subscribeWith(messageSubscriber); } else { messageSubscriber.queueWork(work); } LOGGER.atVerbose() .addKeyValue(WORK_ID_KEY, work.getId()) .log("Receive request queued up."); } void renewSessionLock(String sessionId, Duration maxLockRenewalDuration, Consumer<Throwable> onError) { final Consumer<Throwable> throwableConsumer = onError != null ? onError : error -> LOGGER.atWarning().addKeyValue(SESSION_ID_KEY, sessionId).log("Exception occurred while renewing session.", error); asyncClient.renewSessionLock(maxLockRenewalDuration).subscribe( v -> LOGGER.atVerbose().addKeyValue(SESSION_ID_KEY, sessionId).log("Completed renewing session"), throwableConsumer, () -> LOGGER.atVerbose().addKeyValue(SESSION_ID_KEY, sessionId).log("Auto session lock renewal operation completed.")); } private <T> IterableStream<T> fromFluxAndSubscribe(Flux<T> flux) { Flux<T> cached = flux.cache(); cached.subscribe(); return new IterableStream<>(cached); } }
class ServiceBusReceiverClient implements AutoCloseable { private static final ClientLogger LOGGER = new ClientLogger(ServiceBusReceiverClient.class); private final AtomicInteger idGenerator = new AtomicInteger(); private final ServiceBusReceiverAsyncClient asyncClient; private final Duration operationTimeout; private final boolean isPrefetchDisabled; /* To hold each receive work item to be processed.*/ private final AtomicReference<SynchronousMessageSubscriber> synchronousMessageSubscriber = new AtomicReference<>(); /* To ensure synchronousMessageSubscriber is subscribed only once. */ private final AtomicBoolean syncSubscribed = new AtomicBoolean(false); private final ServiceBusTracer tracer; /** * Creates a synchronous receiver given its asynchronous counterpart. * * @param asyncClient Asynchronous receiver. * @param isPrefetchDisabled Indicates if the prefetch is disabled. * @param operationTimeout Timeout to wait for operation to complete. */ ServiceBusReceiverClient(ServiceBusReceiverAsyncClient asyncClient, boolean isPrefetchDisabled, Duration operationTimeout) { this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); this.isPrefetchDisabled = isPrefetchDisabled; this.tracer = asyncClient.getInstrumentation().getTracer(); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return asyncClient.getFullyQualifiedNamespace(); } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return asyncClient.getEntityPath(); } /** * Gets the SessionId of the session if this receiver is a session receiver. * * @return The SessionId or null if this is not a session receiver. */ public String getSessionId() { return asyncClient.getSessionId(); } /** * Gets the identifier of the instance of {@link ServiceBusReceiverClient}. * * @return The identifier that can identify the instance of {@link ServiceBusReceiverClient}. */ public String getIdentifier() { return asyncClient.getIdentifier(); } /** * Abandons a {@link ServiceBusReceivedMessage message}. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public void abandon(ServiceBusReceivedMessage message) { asyncClient.abandon(message).block(operationTimeout); } /** * Abandons a {@link ServiceBusReceivedMessage message} and updates the message's properties. This will make the * message available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options The options to set while abandoning the message. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverClient * @throws IllegalStateException if receiver is already disposed. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @throws ServiceBusException if the message could not be abandoned. */ public void abandon(ServiceBusReceivedMessage message, AbandonOptions options) { asyncClient.abandon(message, options).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverClient * @throws IllegalStateException if receiver is already disposed. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @throws ServiceBusException if the message could not be completed. */ public void complete(ServiceBusReceivedMessage message) { asyncClient.complete(message).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to complete the message. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverClient * @throws IllegalStateException if receiver is already disposed. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @throws ServiceBusException if the message could not be completed. */ public void complete(ServiceBusReceivedMessage message, CompleteOptions options) { asyncClient.complete(message, options).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred subqueue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: */ public void defer(ServiceBusReceivedMessage message) { asyncClient.defer(message).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This * will move message into the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to defer the message. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: */ public void defer(ServiceBusReceivedMessage message, DeferOptions options) { asyncClient.defer(message, options).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public void deadLetter(ServiceBusReceivedMessage message) { asyncClient.deadLetter(message).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue with dead-letter reason, error * description, and/or modified properties. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to dead-letter the message. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverClient * @throws IllegalStateException if the receiver is already disposed of. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public void deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions options) { asyncClient.deadLetter(message, options).block(operationTimeout); } /** * Gets the state of the session if this receiver is a session receiver. * * @return The session state or null if there is no state set for the session. * * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already disposed. * @throws ServiceBusException if the session state could not be acquired. */ public byte[] getSessionState() { return asyncClient.getSessionState().block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peekMessage()} fetches the first active message for this receiver. Each subsequent call fetches the * subsequent message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * * @throws IllegalStateException if the receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * * @see <a href="https: */ public ServiceBusReceivedMessage peekMessage() { return this.peekMessage(asyncClient.getReceiverOptions().getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peekMessage()} fetches the first active message for this receiver. Each subsequent call fetches the * subsequent message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * * @throws IllegalStateException if receiver is already disposed or the receiver is a non-session receiver. * @throws ServiceBusException if an error occurs while peeking at the message. * * @see <a href="https: */ ServiceBusReceivedMessage peekMessage(String sessionId) { return asyncClient.peekMessage(sessionId).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * * @throws IllegalStateException if the receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * * @see <a href="https: */ public ServiceBusReceivedMessage peekMessage(long sequenceNumber) { return this.peekMessage(sequenceNumber, asyncClient.getReceiverOptions().getSessionId()); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * * @see <a href="https: */ ServiceBusReceivedMessage peekMessage(long sequenceNumber, String sessionId) { return asyncClient.peekMessage(sequenceNumber, sessionId).block(operationTimeout); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The maximum number of messages to peek. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if the receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekMessages(int maxMessages) { return this.peekMessages(maxMessages, asyncClient.getReceiverOptions().getSessionId()); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * * @see <a href="https: */ IterableStream<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) { if (maxMessages <= 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = tracer.traceSyncReceive("ServiceBus.peekMessages", asyncClient.peekMessages(maxMessages, sessionId).timeout(operationTimeout)); return fromFluxAndSubscribe(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if the receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber) { return this.peekMessages(maxMessages, sequenceNumber, asyncClient.getReceiverOptions().getSessionId()); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * * @see <a href="https: */ IterableStream<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber, String sessionId) { if (maxMessages <= 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = tracer.traceSyncReceive("ServiceBus.peekMessages", asyncClient.peekMessages(maxMessages, sequenceNumber, sessionId).timeout(operationTimeout)); return fromFluxAndSubscribe(messages); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. The * receive operation will wait for a default 1 minute for receiving a message before it times out. You can * override it by using {@link * * <p> * The client uses an AMQP link underneath to receive the messages; the client will transparently transition * to a new AMQP link if the current one encounters a retriable error. When the client experiences a non-retriable * error or exhausts the retries, the iteration (e.g., forEach) on the {@link IterableStream} returned by the further * invocations of receiveMessages API will throw the error to the application. Once the application receives * this error, the application should reset the client, i.e., close the current {@link ServiceBusReceiverClient} * and create a new client to continue receiving messages. * <br/> * Note: A few examples of non-retriable errors are - the application attempting to connect to a queue that does not * exist, deleting or disabling the queue in the middle of receiving, the user explicitly initiating Geo-DR. * These are certain events where the Service Bus communicates to the client that a non-retriable error occurred. * </p> * * @param maxMessages The maximum number of messages to receive. * * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} is zero or a negative value. * @throws IllegalStateException if the receiver is already disposed. * @throws ServiceBusException if an error occurs while receiving messages. * * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> receiveMessages(int maxMessages) { return receiveMessages(maxMessages, operationTimeout); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. The * default receive mode is {@link ServiceBusReceiveMode * ServiceBusReceiverClient} using {@link ServiceBusReceiverClientBuilder * * <p> * The client uses an AMQP link underneath to receive the messages; the client will transparently transition * to a new AMQP link if the current one encounters a retriable error. When the client experiences a non-retriable * error or exhausts the retries, the iteration (e.g., forEach) on the {@link IterableStream} returned by the further * invocations of receiveMessages API will throw the error to the application. Once the application receives * this error, the application should reset the client, i.e., close the current {@link ServiceBusReceiverClient} * and create a new client to continue receiving messages. * <br/> * Note: A few examples of non-retriable errors are - the application attempting to connect to a queue that does not * exist, deleting or disabling the queue in the middle of receiving, the user explicitly initiating Geo-DR. * These are certain events where the Service Bus communicates to the client that a non-retriable error occurred. * </p> * * @param maxMessages The maximum number of messages to receive. * @param maxWaitTime The time the client waits for receiving a message before it times out. * * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} or {@code maxWaitTime} is zero or a negative value. * @throws IllegalStateException if the receiver is already disposed. * @throws NullPointerException if {@code maxWaitTime} is null. * @throws ServiceBusException if an error occurs while receiving messages. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> receiveMessages(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw LOGGER.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } final Sinks.Many<ServiceBusReceivedMessage> emitter = Sinks.many().replay().all(); queueWork(maxMessages, maxWaitTime, emitter); final Flux<ServiceBusReceivedMessage> messagesFlux = tracer.traceSyncReceive("ServiceBus.receiveMessages", emitter.asFlux()); messagesFlux.subscribe(); return new IterableStream<>(messagesFlux); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber) { return this.receiveDeferredMessage(sequenceNumber, asyncClient.getReceiverOptions().getSessionId()); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. * * @return A deferred message with the matching {@code sequenceNumber}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber, String sessionId) { return asyncClient.receiveDeferredMessage(sequenceNumber, sessionId).block(operationTimeout); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. * * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred messages cannot be received. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers) { return this.receiveDeferredMessageBatch(sequenceNumbers, asyncClient.getReceiverOptions().getSessionId()); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. * * @throws IllegalStateException if receiver is already disposed. * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws ServiceBusException if deferred message cannot be received. */ IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers, String sessionId) { final Flux<ServiceBusReceivedMessage> messages = tracer.traceSyncReceive("ServiceBus.receiveDeferredMessageBatch", asyncClient.receiveDeferredMessages(sequenceNumbers, sessionId).timeout(operationTimeout)); return fromFluxAndSubscribe(messages); } /** * Renews the lock on the specified message. The lock will be renewed based on the setting specified on the entity. * When a message is received in {@link ServiceBusReceiveMode * server for this receiver instance for a duration as specified during the Queue creation (LockDuration). If * processing of the message requires longer than this duration, the lock needs to be renewed. For each renewal, * the lock is reset to the entity's LockDuration value. * * @param message The {@link ServiceBusReceivedMessage} to perform lock renewal. * * @return The new expiration time for the message. * * @throws NullPointerException if {@code message} or {@code message.getLockToken()} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * @throws IllegalStateException if the receiver is a session receiver or receiver is already disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. */ public OffsetDateTime renewMessageLock(ServiceBusReceivedMessage message) { return asyncClient.renewMessageLock(message).block(operationTimeout); } /** * Starts the auto lock renewal for a message with the given lock. * * @param message The {@link ServiceBusReceivedMessage} to perform auto-lock renewal. * @param maxLockRenewalDuration Maximum duration to keep renewing the lock token. * @param onError A function to call when an error occurs during lock renewal. * * @throws NullPointerException if {@code message}, {@code message.getLockToken()}, or * {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a session receiver or the receiver is disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. * @throws ServiceBusException If the message cannot be renewed. */ public void renewMessageLock(ServiceBusReceivedMessage message, Duration maxLockRenewalDuration, Consumer<Throwable> onError) { final String lockToken = message != null ? message.getLockToken() : "null"; final Consumer<Throwable> throwableConsumer = onError != null ? onError : error -> LOGGER.atWarning().addKeyValue(LOCK_TOKEN_KEY, lockToken).log("Exception occurred while renewing lock token.", error); asyncClient.renewMessageLock(message, maxLockRenewalDuration).subscribe( v -> LOGGER.atVerbose().addKeyValue(LOCK_TOKEN_KEY, lockToken).log("Completed renewing lock token."), throwableConsumer, () -> LOGGER.atVerbose().addKeyValue(LOCK_TOKEN_KEY, lockToken).log("Auto message lock renewal operation completed")); } /** * Sets the state of the session if this receiver is a session receiver. * * @return The next expiration time for the session lock. * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already disposed. * @throws ServiceBusException if the session lock cannot be renewed. */ /** * Starts the auto lock renewal for the session that this receiver works for. * * @param maxLockRenewalDuration Maximum duration to keep renewing the session. * @param onError A function to call when an error occurs during lock renewal. * * @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null. * @throws IllegalArgumentException if {@code sessionId} is an empty string or {@code maxLockRenewalDuration} is negative. * @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed. * @throws ServiceBusException if the session lock renewal operation cannot be started. */ public void renewSessionLock(Duration maxLockRenewalDuration, Consumer<Throwable> onError) { this.renewSessionLock(asyncClient.getReceiverOptions().getSessionId(), maxLockRenewalDuration, onError); } /** * Sets the state of the session if this receiver is a session receiver. * * @param sessionState State to set on the session. * * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already disposed. * @throws ServiceBusException if the session state cannot be set. */ public void setSessionState(byte[] sessionState) { asyncClient.setSessionState(sessionState).block(operationTimeout); } /** * Starts a new transaction on Service Bus. The {@link ServiceBusTransactionContext} should be passed along to all * operations that need to be in this transaction. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverclient.committransaction * <pre> * ServiceBusTransactionContext transaction = receiver.createTransaction& * * & * ServiceBusReceivedMessage deferredMessage = receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * receiver.commitTransaction& * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverclient.committransaction * * @return A new {@link ServiceBusTransactionContext}. * * @throws IllegalStateException if the receiver is already disposed. * @throws ServiceBusException if a transaction cannot be created. */ public ServiceBusTransactionContext createTransaction() { return asyncClient.createTransaction().block(operationTimeout); } /** * Commits the transaction and all the operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverclient.committransaction * <pre> * ServiceBusTransactionContext transaction = receiver.createTransaction& * * & * ServiceBusReceivedMessage deferredMessage = receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * receiver.commitTransaction& * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverclient.committransaction * * @param transactionContext The transaction to be commit. * * @throws IllegalStateException if the receiver is already disposed. * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws ServiceBusException if the transaction could not be committed. */ public void commitTransaction(ServiceBusTransactionContext transactionContext) { asyncClient.commitTransaction(transactionContext).block(operationTimeout); } /** * Rollbacks the transaction given and all operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverclient.committransaction * <pre> * ServiceBusTransactionContext transaction = receiver.createTransaction& * * & * ServiceBusReceivedMessage deferredMessage = receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * receiver.commitTransaction& * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverclient.committransaction * * @param transactionContext The transaction to be rollback. * * @throws IllegalStateException if the receiver is already disposed. * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws ServiceBusException if the transaction could not be rolled back. */ public void rollbackTransaction(ServiceBusTransactionContext transactionContext) { asyncClient.rollbackTransaction(transactionContext).block(operationTimeout); } /** * Disposes of the consumer by closing the underlying links to the service. */ @Override public void close() { SynchronousMessageSubscriber messageSubscriber = synchronousMessageSubscriber.get(); if (messageSubscriber != null && !messageSubscriber.isDisposed()) { messageSubscriber.dispose(); } asyncClient.close(); } /** * Given an {@code emitter}, creates a {@link SynchronousMessageSubscriber} to receive messages from Service Bus * entity. */ private void queueWork(int maximumMessageCount, Duration maxWaitTime, Sinks.Many<ServiceBusReceivedMessage> emitter) { final long id = idGenerator.getAndIncrement(); final SynchronousReceiveWork work = new SynchronousReceiveWork(id, maximumMessageCount, maxWaitTime, emitter); SynchronousMessageSubscriber messageSubscriber = synchronousMessageSubscriber.get(); if (messageSubscriber != null) { messageSubscriber.queueWork(work); return; } messageSubscriber = synchronousMessageSubscriber.updateAndGet(subscriber -> { if (subscriber == null) { return new SynchronousMessageSubscriber(asyncClient, work, isPrefetchDisabled, operationTimeout); } else { return subscriber; } }); if (!syncSubscribed.getAndSet(true)) { asyncClient.receiveMessagesNoBackPressure().subscribeWith(messageSubscriber); } else { messageSubscriber.queueWork(work); } LOGGER.atVerbose() .addKeyValue(WORK_ID_KEY, work.getId()) .log("Receive request queued up."); } void renewSessionLock(String sessionId, Duration maxLockRenewalDuration, Consumer<Throwable> onError) { final Consumer<Throwable> throwableConsumer = onError != null ? onError : error -> LOGGER.atWarning().addKeyValue(SESSION_ID_KEY, sessionId).log("Exception occurred while renewing session.", error); asyncClient.renewSessionLock(maxLockRenewalDuration).subscribe( v -> LOGGER.atVerbose().addKeyValue(SESSION_ID_KEY, sessionId).log("Completed renewing session"), throwableConsumer, () -> LOGGER.atVerbose().addKeyValue(SESSION_ID_KEY, sessionId).log("Auto session lock renewal operation completed.")); } private <T> IterableStream<T> fromFluxAndSubscribe(Flux<T> flux) { Flux<T> cached = flux.cache(); cached.subscribe(); return new IterableStream<>(cached); } }
The sample was calling package internal method, fixing it by calling public api
public void run() { final AtomicBoolean isRunning = new AtomicBoolean(true); CountDownLatch countdownLatch = new CountDownLatch(1); Mono.delay(Duration.ofMinutes(1)).subscribe(index -> { System.out.println("1 minutes has elapsed, stopping receive loop."); isRunning.set(false); }); ServiceBusSessionReceiverClient sessionReceiver = new ServiceBusClientBuilder() .connectionString(connectionString) .sessionReceiver() .queueName(queueName) .buildClient(); ServiceBusReceiverClient receiver = sessionReceiver.acceptSession("greetings-id"); byte[] newState = "new".getBytes(StandardCharsets.UTF_8); receiver.setSessionState(newState); byte[] state = receiver.getSessionState(); Assertions.assertArrayEquals(state, newState); try { while (isRunning.get()) { IterableStream<ServiceBusReceivedMessage> messages = receiver.receiveMessages(10, Duration.ofSeconds(20)); for (ServiceBusReceivedMessage message : messages) { boolean isSuccessfullyProcessed = processMessage(message); if (isSuccessfullyProcessed) { receiver.complete(message); } else { receiver.abandon(message, null); } } } } finally { receiver.close(); } sessionReceiver.close(); }
byte[] state = receiver.getSessionState();
public void run() { final AtomicBoolean isRunning = new AtomicBoolean(true); CountDownLatch countdownLatch = new CountDownLatch(1); Mono.delay(Duration.ofMinutes(1)).subscribe(index -> { System.out.println("1 minutes has elapsed, stopping receive loop."); isRunning.set(false); }); ServiceBusSessionReceiverClient sessionReceiver = new ServiceBusClientBuilder() .connectionString(connectionString) .sessionReceiver() .queueName(queueName) .buildClient(); ServiceBusReceiverClient receiver = sessionReceiver.acceptSession("greetings-id"); byte[] newState = "new".getBytes(StandardCharsets.UTF_8); receiver.setSessionState(newState); byte[] state = receiver.getSessionState(); Assertions.assertArrayEquals(state, newState); try { while (isRunning.get()) { IterableStream<ServiceBusReceivedMessage> messages = receiver.receiveMessages(10, Duration.ofSeconds(20)); for (ServiceBusReceivedMessage message : messages) { boolean isSuccessfullyProcessed = processMessage(message); if (isSuccessfullyProcessed) { receiver.complete(message); } else { receiver.abandon(message, null); } } } } finally { receiver.close(); } sessionReceiver.close(); }
class ReceiveNamedSessionSample { String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_SESSION_QUEUE_NAME"); /** * Main method to invoke this demo on how to receive messages from a session with id "greetings" in an Azure Service * Bus Queue. * * @param args Unused arguments to the program. */ public static void main(String[] args) { ReceiveNamedSessionSample sample = new ReceiveNamedSessionSample(); sample.run(); } /** * This method to invoke this demo on how to receive messages from a session with id "greetings" in an Azure Service * Bus Queue. */ @Test private static boolean processMessage(ServiceBusReceivedMessage message) { System.out.printf("Session: %s. Sequence message.getSequenceNumber(), message.getBody()); return true; } }
class ReceiveNamedSessionSample { String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_SESSION_QUEUE_NAME"); /** * Main method to invoke this demo on how to receive messages from a session with id "greetings" in an Azure Service * Bus Queue. * * @param args Unused arguments to the program. */ public static void main(String[] args) { ReceiveNamedSessionSample sample = new ReceiveNamedSessionSample(); sample.run(); } /** * This method to invoke this demo on how to receive messages from a session with id "greetings" in an Azure Service * Bus Queue. */ @Test private static boolean processMessage(ServiceBusReceivedMessage message) { System.out.printf("Session: %s. Sequence message.getSequenceNumber(), message.getBody()); return true; } }
Need to add matchers ``` if (interceptorManager.isPLaybackMode()) { interceptorManager.addMatchers(Arrays.asList(new BodilessMatcher(), new CustomMatcher().setHeadersKeyOnlyMatch("repeatability-first-sent", "repeatability-request-id", "x-ms-content-sha256", "x-ms-hmac-string-to-sign-base64"))) } ```
protected RoomsClientBuilder getRoomsClient(HttpClient httpClient) { CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString( CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); String communicationAccessKey = communicationConnectionString.getAccessKey(); RoomsClientBuilder builder = new RoomsClientBuilder(); builder.endpoint(communicationEndpoint).credential(new AzureKeyCredential(communicationAccessKey)) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } return builder; }
}
protected RoomsClientBuilder getRoomsClient(HttpClient httpClient) { CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString( CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); String communicationAccessKey = communicationConnectionString.getAccessKey(); RoomsClientBuilder builder = new RoomsClientBuilder(); builder.endpoint(communicationEndpoint).credential(new AzureKeyCredential(communicationAccessKey)) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); configureTestMode(builder); return builder; }
class RoomsTestBase extends TestProxyTestBase { protected static final TestMode TEST_MODE = initializeTestMode(); protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration().get( "COMMUNICATION_CONNECTION_STRING_ROOMS", "endpoint=https: protected static final OffsetDateTime VALID_FROM = OffsetDateTime.now(); protected static final OffsetDateTime VALID_UNTIL = VALID_FROM.plusDays(30); protected RoomsClientBuilder getRoomsClientWithToken(HttpClient httpClient, TokenCredential tokenCredential) { if (getTestMode() == TestMode.PLAYBACK) { tokenCredential = new MockTokenCredential(); } RoomsClientBuilder builder = new RoomsClientBuilder(); builder.endpoint(new CommunicationConnectionString(CONNECTION_STRING).getEndpoint()).credential(tokenCredential) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } return builder; } protected RoomsClientBuilder getRoomsClientWithConnectionString(HttpClient httpClient, RoomsServiceVersion version) { RoomsClientBuilder builder = new RoomsClientBuilder(); builder.connectionString(CONNECTION_STRING) .serviceVersion(version) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } return builder; } protected CommunicationIdentityClientBuilder getCommunicationIdentityClientBuilder(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(CONNECTION_STRING); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); builder.endpoint(endpoint) .credential(new AzureKeyCredential(accessKey)) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } return builder; } private static TestMode initializeTestMode() { ClientLogger logger = new ClientLogger(RoomsTestBase.class); String azureTestMode = Configuration.getGlobalConfiguration().get("AZURE_TEST_MODE"); if (azureTestMode != null) { System.out.println("azureTestMode: " + azureTestMode); try { return TestMode.valueOf(azureTestMode.toUpperCase(Locale.US)); } catch (IllegalArgumentException var3) { logger.error("Could not parse '{}' into TestEnum. Using 'Playback' mode.", azureTestMode); return TestMode.PLAYBACK; } } else { logger.info("Environment variable '{}' has not been set yet. Using 'Playback' mode.", "AZURE_TEST_MODE"); return TestMode.PLAYBACK; } } protected RoomsClientBuilder addLoggingPolicy(RoomsClientBuilder builder, String testName) { return builder.addPolicy((context, next) -> logHeaders(testName, next)); } protected void assertHappyPath(CommunicationRoom roomResult) { assertNotNull(roomResult.getRoomId()); assertNotNull(roomResult.getValidUntil()); assertNotNull(roomResult.getValidFrom()); assertNotNull(roomResult.getCreatedAt()); } protected void assertHappyPath(Response<CommunicationRoom> roomResult, int httpStatusCode) { assertEquals(roomResult.getStatusCode(), httpStatusCode); assertNotNull(roomResult.getValue().getRoomId()); assertNotNull(roomResult.getValue().getValidUntil()); assertNotNull(roomResult.getValue().getValidFrom()); assertNotNull(roomResult.getValue().getCreatedAt()); } private Mono<HttpResponse> logHeaders(String testName, HttpPipelineNextPolicy next) { return next.process().flatMap(httpResponse -> { final HttpResponse bufferedResponse = httpResponse.buffer(); System.out.println("MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); } static class MockTokenCredential implements TokenCredential { @Override public Mono<AccessToken> getToken(TokenRequestContext tokenRequestContext) { return Mono.just(new AccessToken("someFakeToken", OffsetDateTime.MAX)); } } private String redact(String content, Matcher matcher, String replacement) { while (matcher.find()) { String captureGroup = matcher.group(1); if (!CoreUtils.isNullOrEmpty(captureGroup)) { content = content.replace(matcher.group(1), replacement); } } return content; } protected boolean areParticipantsEqual(RoomParticipant participant1, RoomParticipant participant2) { return participant1.getCommunicationIdentifier().getRawId() .equals(participant1.getCommunicationIdentifier().getRawId()) && participant1.getRole().toString().equals(participant2.getRole().toString()); } }
class RoomsTestBase extends TestProxyTestBase { protected static final TestMode TEST_MODE = initializeTestMode(); protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration().get( "COMMUNICATION_CONNECTION_STRING_ROOMS", "endpoint=https: protected static final OffsetDateTime VALID_FROM = OffsetDateTime.now(); protected static final OffsetDateTime VALID_UNTIL = VALID_FROM.plusDays(30); protected RoomsClientBuilder getRoomsClientWithToken(HttpClient httpClient, TokenCredential tokenCredential) { if (getTestMode() == TestMode.PLAYBACK) { tokenCredential = new MockTokenCredential(); } RoomsClientBuilder builder = new RoomsClientBuilder(); builder.endpoint(new CommunicationConnectionString(CONNECTION_STRING).getEndpoint()).credential(tokenCredential) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); configureTestMode(builder); return builder; } protected RoomsClientBuilder getRoomsClientWithConnectionString(HttpClient httpClient, RoomsServiceVersion version) { RoomsClientBuilder builder = new RoomsClientBuilder(); builder.connectionString(CONNECTION_STRING) .serviceVersion(version) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); configureTestMode(builder); return builder; } protected CommunicationIdentityClientBuilder getCommunicationIdentityClientBuilder(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(CONNECTION_STRING); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); builder.endpoint(endpoint) .credential(new AzureKeyCredential(accessKey)) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } if (interceptorManager.isPlaybackMode()) { interceptorManager.addMatchers(Arrays.asList(new BodilessMatcher(), new CustomMatcher().setHeadersKeyOnlyMatch(Arrays.asList("repeatability-first-sent", "repeatability-request-id", "x-ms-content-sha256", "x-ms-hmac-string-to-sign-base64")))); } return builder; } protected void configureTestMode(RoomsClientBuilder builder) { if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } if (interceptorManager.isPlaybackMode()) { interceptorManager.addMatchers(Arrays.asList(new BodilessMatcher(), new CustomMatcher().setHeadersKeyOnlyMatch(Arrays.asList("repeatability-first-sent", "repeatability-request-id", "x-ms-content-sha256", "x-ms-hmac-string-to-sign-base64")))); } } private static TestMode initializeTestMode() { ClientLogger logger = new ClientLogger(RoomsTestBase.class); String azureTestMode = Configuration.getGlobalConfiguration().get("AZURE_TEST_MODE"); if (azureTestMode != null) { System.out.println("azureTestMode: " + azureTestMode); try { return TestMode.valueOf(azureTestMode.toUpperCase(Locale.US)); } catch (IllegalArgumentException var3) { logger.error("Could not parse '{}' into TestEnum. Using 'Playback' mode.", azureTestMode); return TestMode.PLAYBACK; } } else { logger.info("Environment variable '{}' has not been set yet. Using 'Playback' mode.", "AZURE_TEST_MODE"); return TestMode.PLAYBACK; } } protected RoomsClientBuilder addLoggingPolicy(RoomsClientBuilder builder, String testName) { return builder.addPolicy((context, next) -> logHeaders(testName, next)); } protected void assertHappyPath(CommunicationRoom roomResult) { assertNotNull(roomResult.getRoomId()); assertNotNull(roomResult.getValidUntil()); assertNotNull(roomResult.getValidFrom()); assertNotNull(roomResult.getCreatedAt()); } protected void assertHappyPath(Response<CommunicationRoom> roomResult, int httpStatusCode) { assertEquals(roomResult.getStatusCode(), httpStatusCode); assertNotNull(roomResult.getValue().getRoomId()); assertNotNull(roomResult.getValue().getValidUntil()); assertNotNull(roomResult.getValue().getValidFrom()); assertNotNull(roomResult.getValue().getCreatedAt()); } private Mono<HttpResponse> logHeaders(String testName, HttpPipelineNextPolicy next) { return next.process().flatMap(httpResponse -> { final HttpResponse bufferedResponse = httpResponse.buffer(); System.out.println("MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); } protected boolean areParticipantsEqual(RoomParticipant participant1, RoomParticipant participant2) { return participant1.getCommunicationIdentifier().getRawId() .equals(participant1.getCommunicationIdentifier().getRawId()) && participant1.getRole().toString().equals(participant2.getRole().toString()); } }
revert and remove FakeCredentials,
private Mono<HttpResponse> logHeaders(String testName, HttpPipelineNextPolicy next) { return next.process().flatMap(httpResponse -> { final HttpResponse bufferedResponse = httpResponse.buffer(); System.out.println("MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); }
private Mono<HttpResponse> logHeaders(String testName, HttpPipelineNextPolicy next) { return next.process().flatMap(httpResponse -> { final HttpResponse bufferedResponse = httpResponse.buffer(); System.out.println("MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); }
class RoomsTestBase extends TestProxyTestBase { protected static final TestMode TEST_MODE = initializeTestMode(); protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration().get( "COMMUNICATION_CONNECTION_STRING_ROOMS", "endpoint=https: protected static final OffsetDateTime VALID_FROM = OffsetDateTime.now(); protected static final OffsetDateTime VALID_UNTIL = VALID_FROM.plusDays(30); protected RoomsClientBuilder getRoomsClient(HttpClient httpClient) { CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString( CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); String communicationAccessKey = communicationConnectionString.getAccessKey(); RoomsClientBuilder builder = new RoomsClientBuilder(); builder.endpoint(communicationEndpoint).credential(new AzureKeyCredential(communicationAccessKey)) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } return builder; } protected RoomsClientBuilder getRoomsClientWithToken(HttpClient httpClient, TokenCredential tokenCredential) { if (getTestMode() == TestMode.PLAYBACK) { tokenCredential = new MockTokenCredential(); } RoomsClientBuilder builder = new RoomsClientBuilder(); builder.endpoint(new CommunicationConnectionString(CONNECTION_STRING).getEndpoint()).credential(tokenCredential) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } return builder; } protected RoomsClientBuilder getRoomsClientWithConnectionString(HttpClient httpClient, RoomsServiceVersion version) { RoomsClientBuilder builder = new RoomsClientBuilder(); builder.connectionString(CONNECTION_STRING) .serviceVersion(version) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } return builder; } protected CommunicationIdentityClientBuilder getCommunicationIdentityClientBuilder(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(CONNECTION_STRING); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); builder.endpoint(endpoint) .credential(new AzureKeyCredential(accessKey)) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } return builder; } private static TestMode initializeTestMode() { ClientLogger logger = new ClientLogger(RoomsTestBase.class); String azureTestMode = Configuration.getGlobalConfiguration().get("AZURE_TEST_MODE"); if (azureTestMode != null) { System.out.println("azureTestMode: " + azureTestMode); try { return TestMode.valueOf(azureTestMode.toUpperCase(Locale.US)); } catch (IllegalArgumentException var3) { logger.error("Could not parse '{}' into TestEnum. Using 'Playback' mode.", azureTestMode); return TestMode.PLAYBACK; } } else { logger.info("Environment variable '{}' has not been set yet. Using 'Playback' mode.", "AZURE_TEST_MODE"); return TestMode.PLAYBACK; } } protected RoomsClientBuilder addLoggingPolicy(RoomsClientBuilder builder, String testName) { return builder.addPolicy((context, next) -> logHeaders(testName, next)); } protected void assertHappyPath(CommunicationRoom roomResult) { assertNotNull(roomResult.getRoomId()); assertNotNull(roomResult.getValidUntil()); assertNotNull(roomResult.getValidFrom()); assertNotNull(roomResult.getCreatedAt()); } protected void assertHappyPath(Response<CommunicationRoom> roomResult, int httpStatusCode) { assertEquals(roomResult.getStatusCode(), httpStatusCode); assertNotNull(roomResult.getValue().getRoomId()); assertNotNull(roomResult.getValue().getValidUntil()); assertNotNull(roomResult.getValue().getValidFrom()); assertNotNull(roomResult.getValue().getCreatedAt()); } static class MockTokenCredential implements TokenCredential { @Override public Mono<AccessToken> getToken(TokenRequestContext tokenRequestContext) { return Mono.just(new AccessToken("someFakeToken", OffsetDateTime.MAX)); } } private String redact(String content, Matcher matcher, String replacement) { while (matcher.find()) { String captureGroup = matcher.group(1); if (!CoreUtils.isNullOrEmpty(captureGroup)) { content = content.replace(matcher.group(1), replacement); } } return content; } protected boolean areParticipantsEqual(RoomParticipant participant1, RoomParticipant participant2) { return participant1.getCommunicationIdentifier().getRawId() .equals(participant1.getCommunicationIdentifier().getRawId()) && participant1.getRole().toString().equals(participant2.getRole().toString()); } }
class RoomsTestBase extends TestProxyTestBase { protected static final TestMode TEST_MODE = initializeTestMode(); protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration().get( "COMMUNICATION_CONNECTION_STRING_ROOMS", "endpoint=https: protected static final OffsetDateTime VALID_FROM = OffsetDateTime.now(); protected static final OffsetDateTime VALID_UNTIL = VALID_FROM.plusDays(30); protected RoomsClientBuilder getRoomsClient(HttpClient httpClient) { CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString( CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); String communicationAccessKey = communicationConnectionString.getAccessKey(); RoomsClientBuilder builder = new RoomsClientBuilder(); builder.endpoint(communicationEndpoint).credential(new AzureKeyCredential(communicationAccessKey)) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); configureTestMode(builder); return builder; } protected RoomsClientBuilder getRoomsClientWithToken(HttpClient httpClient, TokenCredential tokenCredential) { if (getTestMode() == TestMode.PLAYBACK) { tokenCredential = new MockTokenCredential(); } RoomsClientBuilder builder = new RoomsClientBuilder(); builder.endpoint(new CommunicationConnectionString(CONNECTION_STRING).getEndpoint()).credential(tokenCredential) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); configureTestMode(builder); return builder; } protected RoomsClientBuilder getRoomsClientWithConnectionString(HttpClient httpClient, RoomsServiceVersion version) { RoomsClientBuilder builder = new RoomsClientBuilder(); builder.connectionString(CONNECTION_STRING) .serviceVersion(version) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); configureTestMode(builder); return builder; } protected CommunicationIdentityClientBuilder getCommunicationIdentityClientBuilder(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(CONNECTION_STRING); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); builder.endpoint(endpoint) .credential(new AzureKeyCredential(accessKey)) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } if (interceptorManager.isPlaybackMode()) { interceptorManager.addMatchers(Arrays.asList(new BodilessMatcher(), new CustomMatcher().setHeadersKeyOnlyMatch(Arrays.asList("repeatability-first-sent", "repeatability-request-id", "x-ms-content-sha256", "x-ms-hmac-string-to-sign-base64")))); } return builder; } protected void configureTestMode(RoomsClientBuilder builder) { if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } if (interceptorManager.isPlaybackMode()) { interceptorManager.addMatchers(Arrays.asList(new BodilessMatcher(), new CustomMatcher().setHeadersKeyOnlyMatch(Arrays.asList("repeatability-first-sent", "repeatability-request-id", "x-ms-content-sha256", "x-ms-hmac-string-to-sign-base64")))); } } private static TestMode initializeTestMode() { ClientLogger logger = new ClientLogger(RoomsTestBase.class); String azureTestMode = Configuration.getGlobalConfiguration().get("AZURE_TEST_MODE"); if (azureTestMode != null) { System.out.println("azureTestMode: " + azureTestMode); try { return TestMode.valueOf(azureTestMode.toUpperCase(Locale.US)); } catch (IllegalArgumentException var3) { logger.error("Could not parse '{}' into TestEnum. Using 'Playback' mode.", azureTestMode); return TestMode.PLAYBACK; } } else { logger.info("Environment variable '{}' has not been set yet. Using 'Playback' mode.", "AZURE_TEST_MODE"); return TestMode.PLAYBACK; } } protected RoomsClientBuilder addLoggingPolicy(RoomsClientBuilder builder, String testName) { return builder.addPolicy((context, next) -> logHeaders(testName, next)); } protected void assertHappyPath(CommunicationRoom roomResult) { assertNotNull(roomResult.getRoomId()); assertNotNull(roomResult.getValidUntil()); assertNotNull(roomResult.getValidFrom()); assertNotNull(roomResult.getCreatedAt()); } protected void assertHappyPath(Response<CommunicationRoom> roomResult, int httpStatusCode) { assertEquals(roomResult.getStatusCode(), httpStatusCode); assertNotNull(roomResult.getValue().getRoomId()); assertNotNull(roomResult.getValue().getValidUntil()); assertNotNull(roomResult.getValue().getValidFrom()); assertNotNull(roomResult.getValue().getCreatedAt()); } protected boolean areParticipantsEqual(RoomParticipant participant1, RoomParticipant participant2) { return participant1.getCommunicationIdentifier().getRawId() .equals(participant1.getCommunicationIdentifier().getRawId()) && participant1.getRole().toString().equals(participant2.getRole().toString()); } }
Added.
protected RoomsClientBuilder getRoomsClient(HttpClient httpClient) { CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString( CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); String communicationAccessKey = communicationConnectionString.getAccessKey(); RoomsClientBuilder builder = new RoomsClientBuilder(); builder.endpoint(communicationEndpoint).credential(new AzureKeyCredential(communicationAccessKey)) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } return builder; }
}
protected RoomsClientBuilder getRoomsClient(HttpClient httpClient) { CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString( CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); String communicationAccessKey = communicationConnectionString.getAccessKey(); RoomsClientBuilder builder = new RoomsClientBuilder(); builder.endpoint(communicationEndpoint).credential(new AzureKeyCredential(communicationAccessKey)) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); configureTestMode(builder); return builder; }
class RoomsTestBase extends TestProxyTestBase { protected static final TestMode TEST_MODE = initializeTestMode(); protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration().get( "COMMUNICATION_CONNECTION_STRING_ROOMS", "endpoint=https: protected static final OffsetDateTime VALID_FROM = OffsetDateTime.now(); protected static final OffsetDateTime VALID_UNTIL = VALID_FROM.plusDays(30); protected RoomsClientBuilder getRoomsClientWithToken(HttpClient httpClient, TokenCredential tokenCredential) { if (getTestMode() == TestMode.PLAYBACK) { tokenCredential = new MockTokenCredential(); } RoomsClientBuilder builder = new RoomsClientBuilder(); builder.endpoint(new CommunicationConnectionString(CONNECTION_STRING).getEndpoint()).credential(tokenCredential) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } return builder; } protected RoomsClientBuilder getRoomsClientWithConnectionString(HttpClient httpClient, RoomsServiceVersion version) { RoomsClientBuilder builder = new RoomsClientBuilder(); builder.connectionString(CONNECTION_STRING) .serviceVersion(version) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } return builder; } protected CommunicationIdentityClientBuilder getCommunicationIdentityClientBuilder(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(CONNECTION_STRING); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); builder.endpoint(endpoint) .credential(new AzureKeyCredential(accessKey)) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } return builder; } private static TestMode initializeTestMode() { ClientLogger logger = new ClientLogger(RoomsTestBase.class); String azureTestMode = Configuration.getGlobalConfiguration().get("AZURE_TEST_MODE"); if (azureTestMode != null) { System.out.println("azureTestMode: " + azureTestMode); try { return TestMode.valueOf(azureTestMode.toUpperCase(Locale.US)); } catch (IllegalArgumentException var3) { logger.error("Could not parse '{}' into TestEnum. Using 'Playback' mode.", azureTestMode); return TestMode.PLAYBACK; } } else { logger.info("Environment variable '{}' has not been set yet. Using 'Playback' mode.", "AZURE_TEST_MODE"); return TestMode.PLAYBACK; } } protected RoomsClientBuilder addLoggingPolicy(RoomsClientBuilder builder, String testName) { return builder.addPolicy((context, next) -> logHeaders(testName, next)); } protected void assertHappyPath(CommunicationRoom roomResult) { assertNotNull(roomResult.getRoomId()); assertNotNull(roomResult.getValidUntil()); assertNotNull(roomResult.getValidFrom()); assertNotNull(roomResult.getCreatedAt()); } protected void assertHappyPath(Response<CommunicationRoom> roomResult, int httpStatusCode) { assertEquals(roomResult.getStatusCode(), httpStatusCode); assertNotNull(roomResult.getValue().getRoomId()); assertNotNull(roomResult.getValue().getValidUntil()); assertNotNull(roomResult.getValue().getValidFrom()); assertNotNull(roomResult.getValue().getCreatedAt()); } private Mono<HttpResponse> logHeaders(String testName, HttpPipelineNextPolicy next) { return next.process().flatMap(httpResponse -> { final HttpResponse bufferedResponse = httpResponse.buffer(); System.out.println("MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); } static class MockTokenCredential implements TokenCredential { @Override public Mono<AccessToken> getToken(TokenRequestContext tokenRequestContext) { return Mono.just(new AccessToken("someFakeToken", OffsetDateTime.MAX)); } } private String redact(String content, Matcher matcher, String replacement) { while (matcher.find()) { String captureGroup = matcher.group(1); if (!CoreUtils.isNullOrEmpty(captureGroup)) { content = content.replace(matcher.group(1), replacement); } } return content; } protected boolean areParticipantsEqual(RoomParticipant participant1, RoomParticipant participant2) { return participant1.getCommunicationIdentifier().getRawId() .equals(participant1.getCommunicationIdentifier().getRawId()) && participant1.getRole().toString().equals(participant2.getRole().toString()); } }
class RoomsTestBase extends TestProxyTestBase { protected static final TestMode TEST_MODE = initializeTestMode(); protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration().get( "COMMUNICATION_CONNECTION_STRING_ROOMS", "endpoint=https: protected static final OffsetDateTime VALID_FROM = OffsetDateTime.now(); protected static final OffsetDateTime VALID_UNTIL = VALID_FROM.plusDays(30); protected RoomsClientBuilder getRoomsClientWithToken(HttpClient httpClient, TokenCredential tokenCredential) { if (getTestMode() == TestMode.PLAYBACK) { tokenCredential = new MockTokenCredential(); } RoomsClientBuilder builder = new RoomsClientBuilder(); builder.endpoint(new CommunicationConnectionString(CONNECTION_STRING).getEndpoint()).credential(tokenCredential) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); configureTestMode(builder); return builder; } protected RoomsClientBuilder getRoomsClientWithConnectionString(HttpClient httpClient, RoomsServiceVersion version) { RoomsClientBuilder builder = new RoomsClientBuilder(); builder.connectionString(CONNECTION_STRING) .serviceVersion(version) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); configureTestMode(builder); return builder; } protected CommunicationIdentityClientBuilder getCommunicationIdentityClientBuilder(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(CONNECTION_STRING); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); builder.endpoint(endpoint) .credential(new AzureKeyCredential(accessKey)) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } if (interceptorManager.isPlaybackMode()) { interceptorManager.addMatchers(Arrays.asList(new BodilessMatcher(), new CustomMatcher().setHeadersKeyOnlyMatch(Arrays.asList("repeatability-first-sent", "repeatability-request-id", "x-ms-content-sha256", "x-ms-hmac-string-to-sign-base64")))); } return builder; } protected void configureTestMode(RoomsClientBuilder builder) { if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (!interceptorManager.isLiveMode()) { interceptorManager.addSanitizers( Arrays.asList(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY))); } if (interceptorManager.isPlaybackMode()) { interceptorManager.addMatchers(Arrays.asList(new BodilessMatcher(), new CustomMatcher().setHeadersKeyOnlyMatch(Arrays.asList("repeatability-first-sent", "repeatability-request-id", "x-ms-content-sha256", "x-ms-hmac-string-to-sign-base64")))); } } private static TestMode initializeTestMode() { ClientLogger logger = new ClientLogger(RoomsTestBase.class); String azureTestMode = Configuration.getGlobalConfiguration().get("AZURE_TEST_MODE"); if (azureTestMode != null) { System.out.println("azureTestMode: " + azureTestMode); try { return TestMode.valueOf(azureTestMode.toUpperCase(Locale.US)); } catch (IllegalArgumentException var3) { logger.error("Could not parse '{}' into TestEnum. Using 'Playback' mode.", azureTestMode); return TestMode.PLAYBACK; } } else { logger.info("Environment variable '{}' has not been set yet. Using 'Playback' mode.", "AZURE_TEST_MODE"); return TestMode.PLAYBACK; } } protected RoomsClientBuilder addLoggingPolicy(RoomsClientBuilder builder, String testName) { return builder.addPolicy((context, next) -> logHeaders(testName, next)); } protected void assertHappyPath(CommunicationRoom roomResult) { assertNotNull(roomResult.getRoomId()); assertNotNull(roomResult.getValidUntil()); assertNotNull(roomResult.getValidFrom()); assertNotNull(roomResult.getCreatedAt()); } protected void assertHappyPath(Response<CommunicationRoom> roomResult, int httpStatusCode) { assertEquals(roomResult.getStatusCode(), httpStatusCode); assertNotNull(roomResult.getValue().getRoomId()); assertNotNull(roomResult.getValue().getValidUntil()); assertNotNull(roomResult.getValue().getValidFrom()); assertNotNull(roomResult.getValue().getCreatedAt()); } private Mono<HttpResponse> logHeaders(String testName, HttpPipelineNextPolicy next) { return next.process().flatMap(httpResponse -> { final HttpResponse bufferedResponse = httpResponse.buffer(); System.out.println("MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); } protected boolean areParticipantsEqual(RoomParticipant participant1, RoomParticipant participant2) { return participant1.getCommunicationIdentifier().getRawId() .equals(participant1.getCommunicationIdentifier().getRawId()) && participant1.getRole().toString().equals(participant2.getRole().toString()); } }
I think we want this change (maybe we only made it in this repo?)
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; if (httpLogOptions == null) { httpLogOptions = new HttpLogOptions(); } if (clientOptions == null) { clientOptions = new ClientOptions(); } List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault("name", "UnknownName"); String clientVersion = PROPERTIES.getOrDefault("version", "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(clientOptions, httpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); policies.add(new CookiePolicy()); policies.addAll(this.httpPipelinePolicies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); }
policies.add(new HttpLoggingPolicy(httpLogOptions));
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; if (httpLogOptions == null) { httpLogOptions = new HttpLogOptions(); } if (clientOptions == null) { clientOptions = new ClientOptions(); } List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault("name", "UnknownName"); String clientVersion = PROPERTIES.getOrDefault("version", "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(clientOptions, httpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); policies.add(new CookiePolicy()); policies.addAll(this.httpPipelinePolicies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .tracer(new NoopTracer()) .build(); }
class AzureMonitorExporterBuilder { private static final ClientLogger LOGGER = new ClientLogger(AzureMonitorExporterBuilder.class); private static final String APPLICATIONINSIGHTS_CONNECTION_STRING = "APPLICATIONINSIGHTS_CONNECTION_STRING"; private static final String APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE = "https: private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-monitor-opentelemetry-exporter.properties"); private ConnectionString connectionString; private TokenCredential credential; @SuppressWarnings({"UnusedVariable", "FieldCanBeLocal"}) private AzureMonitorExporterServiceVersion serviceVersion; private HttpPipeline httpPipeline; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private RetryPolicy retryPolicy; private final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); private Configuration configuration = Configuration.getGlobalConfiguration(); private ClientOptions clientOptions; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { } /** * Sets the HTTP pipeline to use for the service client. If {@code httpPipeline} is set, all other * settings are ignored. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving * responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpPipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param httpClient The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p>If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param httpLogOptions The logging configuration to use when sending and receiving HTTP * requests/responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * <p>The default retry policy will be used if not provided to build {@link * AzureMonitorExporterBuilder} . * * @param retryPolicy user's retry policy applied to each request. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param httpPipelinePolicy a policy to be added to the http pipeline. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addHttpPipelinePolicy(HttpPipelinePolicy httpPipelinePolicy) { httpPipelinePolicies.add( Objects.requireNonNull(httpPipelinePolicy, "'policy' cannot be null.")); return this; } /** * Sets the configuration store that is used during construction of the service client. * * <p>The default configuration store is a clone of the {@link * Configuration * Configuration * * @param configuration The configuration store used to * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The client options. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the connection string to use for exporting telemetry events to Azure Monitor. * * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ public AzureMonitorExporterBuilder connectionString(String connectionString) { this.connectionString = ConnectionString.parse(connectionString); return this; } /** * Sets the Azure Monitor service version. * * @param serviceVersion The Azure Monitor service version. * @return The update {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder serviceVersion( AzureMonitorExporterServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Sets the token credential required for authentication with the ingestion endpoint service. * * @param credential The Azure Identity TokenCredential. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder credential(TokenCredential credential) { this.credential = credential; return this; } /** * Creates an {@link AzureMonitorTraceExporter} based on the options set in the builder. This * exporter is an implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorTraceExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the * environment variable "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public SpanExporter buildTraceExporter() { SpanDataMapper mapper = new SpanDataMapper( true, this::populateDefaults, (event, instrumentationName) -> false, (span, event) -> false); return new AzureMonitorTraceExporter(mapper, initExporterBuilder()); } /** * Creates an {@link AzureMonitorMetricExporter} based on the options set in the builder. This * exporter is an implementation of OpenTelemetry {@link MetricExporter}. * * <p>When a new {@link MetricExporter} is created, it will automatically start {@link * HeartbeatExporter}. * * @return An instance of {@link AzureMonitorMetricExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the * environment variable "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public MetricExporter buildMetricExporter() { TelemetryItemExporter telemetryItemExporter = initExporterBuilder(); HeartbeatExporter.start( MINUTES.toSeconds(15), this::populateDefaults, telemetryItemExporter::send); return new AzureMonitorMetricExporter( new MetricDataMapper(this::populateDefaults, true), telemetryItemExporter); } /** * Creates an {@link AzureMonitorLogRecordExporter} based on the options set in the builder. This * exporter is an implementation of OpenTelemetry {@link LogRecordExporter}. * * @return An instance of {@link AzureMonitorLogRecordExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the * environment variable "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public LogRecordExporter buildLogRecordExporter() { return new AzureMonitorLogRecordExporter( new LogDataMapper(true, false, this::populateDefaults), initExporterBuilder()); } private TelemetryItemExporter initExporterBuilder() { if (connectionString == null) { Configuration configuration = Configuration.getGlobalConfiguration(); connectionString(configuration.get(APPLICATIONINSIGHTS_CONNECTION_STRING)); } Objects.requireNonNull(connectionString, "'connectionString' cannot be null"); if (this.credential != null) { BearerTokenAuthenticationPolicy authenticationPolicy = new BearerTokenAuthenticationPolicy( this.credential, APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE); httpPipelinePolicies.add(authenticationPolicy); } if (httpPipeline == null) { httpPipeline = createHttpPipeline(); } TelemetryPipeline pipeline = new TelemetryPipeline(httpPipeline); File tempDir = TempDirs.getApplicationInsightsTempDir( LOGGER, "Telemetry will not be stored to disk and retried later" + " on sporadic network failures"); TelemetryItemExporter telemetryItemExporter; if (tempDir != null) { telemetryItemExporter = new TelemetryItemExporter( pipeline, new LocalStorageTelemetryPipelineListener( 50, TempDirs.getSubDir(tempDir, "telemetry"), pipeline, LocalStorageStats.noop(), false)); } else { telemetryItemExporter = new TelemetryItemExporter(pipeline, TelemetryPipelineListener.noop()); } return telemetryItemExporter; } void populateDefaults(AbstractTelemetryBuilder builder, Resource resource) { builder.setConnectionString(connectionString); builder.addTag( ContextTagKeys.AI_INTERNAL_SDK_VERSION.toString(), VersionGenerator.getSdkVersion()); ResourceParser.updateRoleNameAndInstance(builder, resource, configuration); } }
class AzureMonitorExporterBuilder { private static final ClientLogger LOGGER = new ClientLogger(AzureMonitorExporterBuilder.class); private static final String APPLICATIONINSIGHTS_CONNECTION_STRING = "APPLICATIONINSIGHTS_CONNECTION_STRING"; private static final String APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE = "https: private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-monitor-opentelemetry-exporter.properties"); private ConnectionString connectionString; private TokenCredential credential; @SuppressWarnings({"UnusedVariable", "FieldCanBeLocal"}) private AzureMonitorExporterServiceVersion serviceVersion; private HttpPipeline httpPipeline; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private RetryPolicy retryPolicy; private final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); private Configuration configuration = Configuration.getGlobalConfiguration(); private ClientOptions clientOptions; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { } /** * Sets the HTTP pipeline to use for the service client. If {@code httpPipeline} is set, all other * settings are ignored. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving * responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpPipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param httpClient The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p>If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param httpLogOptions The logging configuration to use when sending and receiving HTTP * requests/responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * <p>The default retry policy will be used if not provided to build {@link * AzureMonitorExporterBuilder} . * * @param retryPolicy user's retry policy applied to each request. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param httpPipelinePolicy a policy to be added to the http pipeline. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addHttpPipelinePolicy(HttpPipelinePolicy httpPipelinePolicy) { httpPipelinePolicies.add( Objects.requireNonNull(httpPipelinePolicy, "'policy' cannot be null.")); return this; } /** * Sets the configuration store that is used during construction of the service client. * * <p>The default configuration store is a clone of the {@link * Configuration * Configuration * * @param configuration The configuration store used to * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The client options. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the connection string to use for exporting telemetry events to Azure Monitor. * * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ public AzureMonitorExporterBuilder connectionString(String connectionString) { this.connectionString = ConnectionString.parse(connectionString); return this; } /** * Sets the Azure Monitor service version. * * @param serviceVersion The Azure Monitor service version. * @return The update {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder serviceVersion( AzureMonitorExporterServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Sets the token credential required for authentication with the ingestion endpoint service. * * @param credential The Azure Identity TokenCredential. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder credential(TokenCredential credential) { this.credential = credential; return this; } /** * Creates an {@link AzureMonitorTraceExporter} based on the options set in the builder. This * exporter is an implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorTraceExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the * environment variable "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public SpanExporter buildTraceExporter() { SpanDataMapper mapper = new SpanDataMapper( true, this::populateDefaults, (event, instrumentationName) -> false, (span, event) -> false); return new AzureMonitorTraceExporter(mapper, initExporterBuilder()); } /** * Creates an {@link AzureMonitorMetricExporter} based on the options set in the builder. This * exporter is an implementation of OpenTelemetry {@link MetricExporter}. * * <p>When a new {@link MetricExporter} is created, it will automatically start {@link * HeartbeatExporter}. * * @return An instance of {@link AzureMonitorMetricExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the * environment variable "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public MetricExporter buildMetricExporter() { TelemetryItemExporter telemetryItemExporter = initExporterBuilder(); HeartbeatExporter.start( MINUTES.toSeconds(15), this::populateDefaults, telemetryItemExporter::send); return new AzureMonitorMetricExporter( new MetricDataMapper(this::populateDefaults, true), telemetryItemExporter); } /** * Creates an {@link AzureMonitorLogRecordExporter} based on the options set in the builder. This * exporter is an implementation of OpenTelemetry {@link LogRecordExporter}. * * @return An instance of {@link AzureMonitorLogRecordExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the * environment variable "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public LogRecordExporter buildLogRecordExporter() { return new AzureMonitorLogRecordExporter( new LogDataMapper(true, false, this::populateDefaults), initExporterBuilder()); } private TelemetryItemExporter initExporterBuilder() { if (connectionString == null) { Configuration configuration = Configuration.getGlobalConfiguration(); connectionString(configuration.get(APPLICATIONINSIGHTS_CONNECTION_STRING)); } Objects.requireNonNull(connectionString, "'connectionString' cannot be null"); if (this.credential != null) { BearerTokenAuthenticationPolicy authenticationPolicy = new BearerTokenAuthenticationPolicy( this.credential, APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE); httpPipelinePolicies.add(authenticationPolicy); } if (httpPipeline == null) { httpPipeline = createHttpPipeline(); } TelemetryPipeline pipeline = new TelemetryPipeline(httpPipeline); File tempDir = TempDirs.getApplicationInsightsTempDir( LOGGER, "Telemetry will not be stored to disk and retried later" + " on sporadic network failures"); TelemetryItemExporter telemetryItemExporter; if (tempDir != null) { telemetryItemExporter = new TelemetryItemExporter( pipeline, new LocalStorageTelemetryPipelineListener( 50, TempDirs.getSubDir(tempDir, "telemetry"), pipeline, LocalStorageStats.noop(), false)); } else { telemetryItemExporter = new TelemetryItemExporter(pipeline, TelemetryPipelineListener.noop()); } return telemetryItemExporter; } void populateDefaults(AbstractTelemetryBuilder builder, Resource resource) { builder.setConnectionString(connectionString); builder.addTag( ContextTagKeys.AI_INTERNAL_SDK_VERSION.toString(), VersionGenerator.getSdkVersion()); ResourceParser.updateRoleNameAndInstance(builder, resource, configuration); } }
check history, this change may have been made in this repo
public void run() { try { while (!stopped) { long sleepInMillis; if (pingMode) { sleepInMillis = ping(); } else { sleepInMillis = sendData(); } Thread.sleep(sleepInMillis); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (ThreadDeath td) { throw td; } catch (Throwable t) { } }
public void run() { try { while (!stopped) { long sleepInMillis; if (pingMode) { sleepInMillis = ping(); } else { sleepInMillis = sendData(); } Thread.sleep(sleepInMillis); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable t) { if (t instanceof Error) { throw (Error) t; } } }
class QuickPulseCoordinator implements Runnable { private static final ClientLogger logger = new ClientLogger(QuickPulseCoordinator.class); @Nullable private String qpsServiceRedirectedEndpoint; private long qpsServicePollingIntervalHintMillis; private volatile boolean stopped = false; private volatile boolean pingMode = true; private final QuickPulseDataCollector collector; private final QuickPulsePingSender pingSender; private final QuickPulseDataFetcher dataFetcher; private final QuickPulseDataSender dataSender; private final long waitBetweenPingsInMillis; private final long waitBetweenPostsInMillis; private final long waitOnErrorInMillis; QuickPulseCoordinator(QuickPulseCoordinatorInitData initData) { dataSender = initData.dataSender; pingSender = initData.pingSender; dataFetcher = initData.dataFetcher; collector = initData.collector; waitBetweenPingsInMillis = initData.waitBetweenPingsInMillis; waitBetweenPostsInMillis = initData.waitBetweenPostsInMillis; waitOnErrorInMillis = initData.waitOnErrorInMillis; qpsServiceRedirectedEndpoint = null; qpsServicePollingIntervalHintMillis = -1; } @Override @SuppressWarnings("try") private long sendData() { dataFetcher.prepareQuickPulseDataForSend(qpsServiceRedirectedEndpoint); QuickPulseHeaderInfo currentQuickPulseHeaderInfo = dataSender.getQuickPulseHeaderInfo(); this.handleReceivedHeaders(currentQuickPulseHeaderInfo); collector.setQuickPulseStatus(currentQuickPulseHeaderInfo.getQuickPulseStatus()); switch (currentQuickPulseHeaderInfo.getQuickPulseStatus()) { case ERROR: pingMode = true; return waitOnErrorInMillis; case QP_IS_OFF: pingMode = true; return qpsServicePollingIntervalHintMillis > 0 ? qpsServicePollingIntervalHintMillis : waitBetweenPingsInMillis; case QP_IS_ON: return waitBetweenPostsInMillis; } try (MDC.MDCCloseable ignored = QUICK_PULSE_SEND_ERROR.makeActive()) { logger.error("Critical error while sending QP data: unknown status, aborting"); } collector.disable(); stopped = true; return 0; } @SuppressWarnings("try") private long ping() { QuickPulseHeaderInfo pingResult = pingSender.ping(qpsServiceRedirectedEndpoint); this.handleReceivedHeaders(pingResult); collector.setQuickPulseStatus(pingResult.getQuickPulseStatus()); switch (pingResult.getQuickPulseStatus()) { case ERROR: return waitOnErrorInMillis; case QP_IS_ON: pingMode = false; dataSender.startSending(); return waitBetweenPostsInMillis; case QP_IS_OFF: return qpsServicePollingIntervalHintMillis > 0 ? qpsServicePollingIntervalHintMillis : waitBetweenPingsInMillis; } try (MDC.MDCCloseable ignored = QUICK_PULSE_PING_ERROR.makeActive()) { logger.error("Critical error while ping QP: unknown status, aborting"); } collector.disable(); stopped = true; return 0; } private void handleReceivedHeaders(QuickPulseHeaderInfo currentQuickPulseHeaderInfo) { String redirectLink = currentQuickPulseHeaderInfo.getQpsServiceEndpointRedirect(); if (!Strings.isNullOrEmpty(redirectLink)) { qpsServiceRedirectedEndpoint = redirectLink; } long newPollingInterval = currentQuickPulseHeaderInfo.getQpsServicePollingInterval(); if (newPollingInterval > 0) { qpsServicePollingIntervalHintMillis = newPollingInterval; } } void stop() { stopped = true; } }
class QuickPulseCoordinator implements Runnable { private static final ClientLogger logger = new ClientLogger(QuickPulseCoordinator.class); @Nullable private String qpsServiceRedirectedEndpoint; private long qpsServicePollingIntervalHintMillis; private volatile boolean stopped = false; private volatile boolean pingMode = true; private final QuickPulseDataCollector collector; private final QuickPulsePingSender pingSender; private final QuickPulseDataFetcher dataFetcher; private final QuickPulseDataSender dataSender; private final long waitBetweenPingsInMillis; private final long waitBetweenPostsInMillis; private final long waitOnErrorInMillis; QuickPulseCoordinator(QuickPulseCoordinatorInitData initData) { dataSender = initData.dataSender; pingSender = initData.pingSender; dataFetcher = initData.dataFetcher; collector = initData.collector; waitBetweenPingsInMillis = initData.waitBetweenPingsInMillis; waitBetweenPostsInMillis = initData.waitBetweenPostsInMillis; waitOnErrorInMillis = initData.waitOnErrorInMillis; qpsServiceRedirectedEndpoint = null; qpsServicePollingIntervalHintMillis = -1; } @Override @SuppressWarnings("try") private long sendData() { dataFetcher.prepareQuickPulseDataForSend(qpsServiceRedirectedEndpoint); QuickPulseHeaderInfo currentQuickPulseHeaderInfo = dataSender.getQuickPulseHeaderInfo(); this.handleReceivedHeaders(currentQuickPulseHeaderInfo); collector.setQuickPulseStatus(currentQuickPulseHeaderInfo.getQuickPulseStatus()); switch (currentQuickPulseHeaderInfo.getQuickPulseStatus()) { case ERROR: pingMode = true; return waitOnErrorInMillis; case QP_IS_OFF: pingMode = true; return qpsServicePollingIntervalHintMillis > 0 ? qpsServicePollingIntervalHintMillis : waitBetweenPingsInMillis; case QP_IS_ON: return waitBetweenPostsInMillis; } try (MDC.MDCCloseable ignored = QUICK_PULSE_SEND_ERROR.makeActive()) { logger.error("Critical error while sending QP data: unknown status, aborting"); } collector.disable(); stopped = true; return 0; } @SuppressWarnings("try") private long ping() { QuickPulseHeaderInfo pingResult = pingSender.ping(qpsServiceRedirectedEndpoint); this.handleReceivedHeaders(pingResult); collector.setQuickPulseStatus(pingResult.getQuickPulseStatus()); switch (pingResult.getQuickPulseStatus()) { case ERROR: return waitOnErrorInMillis; case QP_IS_ON: pingMode = false; dataSender.startSending(); return waitBetweenPostsInMillis; case QP_IS_OFF: return qpsServicePollingIntervalHintMillis > 0 ? qpsServicePollingIntervalHintMillis : waitBetweenPingsInMillis; } try (MDC.MDCCloseable ignored = QUICK_PULSE_PING_ERROR.makeActive()) { logger.error("Critical error while ping QP: unknown status, aborting"); } collector.disable(); stopped = true; return 0; } private void handleReceivedHeaders(QuickPulseHeaderInfo currentQuickPulseHeaderInfo) { String redirectLink = currentQuickPulseHeaderInfo.getQpsServiceEndpointRedirect(); if (!Strings.isNullOrEmpty(redirectLink)) { qpsServiceRedirectedEndpoint = redirectLink; } long newPollingInterval = currentQuickPulseHeaderInfo.getQpsServicePollingInterval(); if (newPollingInterval > 0) { qpsServicePollingIntervalHintMillis = newPollingInterval; } } void stop() { stopped = true; } }
same for these other ThreadDeath changes
public void prepareQuickPulseDataForSend(String redirectedEndpoint) { try { QuickPulseDataCollector.FinalCounters counters = collector.getAndRestart(); if (counters == null) { return; } Date currentDate = new Date(); String endpointPrefix = Strings.isNullOrEmpty(redirectedEndpoint) ? getQuickPulseEndpoint() : redirectedEndpoint; HttpRequest request = networkHelper.buildRequest(currentDate, this.getEndpointUrl(endpointPrefix)); request.setBody(buildPostEntity(counters)); if (!sendQueue.offer(request)) { logger.verbose("Quick Pulse send queue is full"); } } catch (ThreadDeath td) { throw td; } catch (Throwable e) { try { try (MDC.MDCCloseable ignored = QUICK_PULSE_SEND_ERROR.makeActive()) { logger.error("Quick Pulse failed to prepare data for send", e); } } catch (ThreadDeath td) { throw td; } catch (Throwable t2) { } } }
}
public void prepareQuickPulseDataForSend(String redirectedEndpoint) { try { QuickPulseDataCollector.FinalCounters counters = collector.getAndRestart(); if (counters == null) { return; } Date currentDate = new Date(); String endpointPrefix = Strings.isNullOrEmpty(redirectedEndpoint) ? getQuickPulseEndpoint() : redirectedEndpoint; HttpRequest request = networkHelper.buildRequest(currentDate, this.getEndpointUrl(endpointPrefix)); request.setBody(buildPostEntity(counters)); if (!sendQueue.offer(request)) { logger.verbose("Quick Pulse send queue is full"); } } catch (Throwable e) { if (e instanceof Error) { throw (Error) e; } try { try (MDC.MDCCloseable ignored = QUICK_PULSE_SEND_ERROR.makeActive()) { logger.error("Quick Pulse failed to prepare data for send", e); } } catch (Throwable t2) { if (t2 instanceof Error) { throw (Error) t2; } } } }
class QuickPulseDataFetcher { private static final ClientLogger logger = new ClientLogger(QuickPulseDataFetcher.class); private static final ObjectMapper mapper; static { mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.getFactory().setCharacterEscapes(new CustomCharacterEscapes()); } private final QuickPulseDataCollector collector; private final ArrayBlockingQueue<HttpRequest> sendQueue; private final QuickPulseNetworkHelper networkHelper = new QuickPulseNetworkHelper(); private final Supplier<URL> endpointUrl; private final Supplier<String> instrumentationKey; private final String roleName; private final String instanceName; private final String machineName; private final String quickPulseId; private final String sdkVersion; public QuickPulseDataFetcher( QuickPulseDataCollector collector, ArrayBlockingQueue<HttpRequest> sendQueue, Supplier<URL> endpointUrl, Supplier<String> instrumentationKey, String roleName, String instanceName, String machineName, String quickPulseId) { this.collector = collector; this.sendQueue = sendQueue; this.endpointUrl = endpointUrl; this.instrumentationKey = instrumentationKey; this.roleName = roleName; this.instanceName = instanceName; this.machineName = machineName; this.quickPulseId = quickPulseId; sdkVersion = getCurrentSdkVersion(); } /** * Returns SDK Version from properties. */ String getCurrentSdkVersion() { return "unknown"; } @SuppressWarnings("try") String getEndpointUrl(String endpointPrefix) { return endpointPrefix + "/post?ikey=" + instrumentationKey.get(); } String getQuickPulseEndpoint() { return endpointUrl.get().toString() + "QuickPulseService.svc"; } private String buildPostEntity(QuickPulseDataCollector.FinalCounters counters) throws JsonProcessingException { List<QuickPulseEnvelope> envelopes = new ArrayList<>(); QuickPulseEnvelope postEnvelope = new QuickPulseEnvelope(); postEnvelope.setDocuments(counters.documentList); postEnvelope.setInstance(instanceName); postEnvelope.setInvariantVersion(QuickPulse.QP_INVARIANT_VERSION); postEnvelope.setMachineName(machineName); postEnvelope.setRoleName(roleName); postEnvelope.setInstrumentationKey(instrumentationKey.get()); postEnvelope.setStreamId(quickPulseId); postEnvelope.setVersion(sdkVersion); postEnvelope.setTimeStamp("/Date(" + System.currentTimeMillis() + ")/"); postEnvelope.setMetrics(addMetricsToQuickPulseEnvelope(counters)); envelopes.add(postEnvelope); return mapper.writeValueAsString(envelopes); } private static List<QuickPulseMetrics> addMetricsToQuickPulseEnvelope( QuickPulseDataCollector.FinalCounters counters) { List<QuickPulseMetrics> metricsList = new ArrayList<>(); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Requests/Sec", counters.requests, 1)); if (counters.requests != 0) { metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Request Duration", counters.requestsDuration / counters.requests, counters.requests)); } metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Requests Failed/Sec", counters.unsuccessfulRequests, 1)); metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Requests Succeeded/Sec", counters.requests - counters.unsuccessfulRequests, 1)); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Dependency Calls/Sec", counters.rdds, 1)); if (counters.rdds != 0) { metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Call Duration", counters.rddsDuration / counters.rdds, (int) counters.rdds)); } metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Calls Failed/Sec", counters.unsuccessfulRdds, 1)); metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Calls Succeeded/Sec", counters.rdds - counters.unsuccessfulRdds, 1)); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Exceptions/Sec", counters.exceptions, 1)); metricsList.add( new QuickPulseMetrics("\\Memory\\Committed Bytes", counters.memoryCommitted, 1)); metricsList.add( new QuickPulseMetrics("\\Processor(_Total)\\% Processor Time", counters.cpuUsage, 1)); return metricsList; } }
class QuickPulseDataFetcher { private static final ClientLogger logger = new ClientLogger(QuickPulseDataFetcher.class); private static final ObjectMapper mapper; static { mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.getFactory().setCharacterEscapes(new CustomCharacterEscapes()); } private final QuickPulseDataCollector collector; private final ArrayBlockingQueue<HttpRequest> sendQueue; private final QuickPulseNetworkHelper networkHelper = new QuickPulseNetworkHelper(); private final Supplier<URL> endpointUrl; private final Supplier<String> instrumentationKey; private final String roleName; private final String instanceName; private final String machineName; private final String quickPulseId; private final String sdkVersion; public QuickPulseDataFetcher( QuickPulseDataCollector collector, ArrayBlockingQueue<HttpRequest> sendQueue, Supplier<URL> endpointUrl, Supplier<String> instrumentationKey, String roleName, String instanceName, String machineName, String quickPulseId) { this.collector = collector; this.sendQueue = sendQueue; this.endpointUrl = endpointUrl; this.instrumentationKey = instrumentationKey; this.roleName = roleName; this.instanceName = instanceName; this.machineName = machineName; this.quickPulseId = quickPulseId; sdkVersion = getCurrentSdkVersion(); } /** * Returns SDK Version from properties. */ String getCurrentSdkVersion() { return "unknown"; } @SuppressWarnings("try") String getEndpointUrl(String endpointPrefix) { return endpointPrefix + "/post?ikey=" + instrumentationKey.get(); } String getQuickPulseEndpoint() { return endpointUrl.get().toString() + "QuickPulseService.svc"; } private String buildPostEntity(QuickPulseDataCollector.FinalCounters counters) throws JsonProcessingException { List<QuickPulseEnvelope> envelopes = new ArrayList<>(); QuickPulseEnvelope postEnvelope = new QuickPulseEnvelope(); postEnvelope.setDocuments(counters.documentList); postEnvelope.setInstance(instanceName); postEnvelope.setInvariantVersion(QuickPulse.QP_INVARIANT_VERSION); postEnvelope.setMachineName(machineName); postEnvelope.setRoleName(roleName); postEnvelope.setInstrumentationKey(instrumentationKey.get()); postEnvelope.setStreamId(quickPulseId); postEnvelope.setVersion(sdkVersion); postEnvelope.setTimeStamp("/Date(" + System.currentTimeMillis() + ")/"); postEnvelope.setMetrics(addMetricsToQuickPulseEnvelope(counters)); envelopes.add(postEnvelope); return mapper.writeValueAsString(envelopes); } private static List<QuickPulseMetrics> addMetricsToQuickPulseEnvelope( QuickPulseDataCollector.FinalCounters counters) { List<QuickPulseMetrics> metricsList = new ArrayList<>(); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Requests/Sec", counters.requests, 1)); if (counters.requests != 0) { metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Request Duration", counters.requestsDuration / counters.requests, counters.requests)); } metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Requests Failed/Sec", counters.unsuccessfulRequests, 1)); metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Requests Succeeded/Sec", counters.requests - counters.unsuccessfulRequests, 1)); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Dependency Calls/Sec", counters.rdds, 1)); if (counters.rdds != 0) { metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Call Duration", counters.rddsDuration / counters.rdds, (int) counters.rdds)); } metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Calls Failed/Sec", counters.unsuccessfulRdds, 1)); metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Calls Succeeded/Sec", counters.rdds - counters.unsuccessfulRdds, 1)); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Exceptions/Sec", counters.exceptions, 1)); metricsList.add( new QuickPulseMetrics("\\Memory\\Committed Bytes", counters.memoryCommitted, 1)); metricsList.add( new QuickPulseMetrics("\\Processor(_Total)\\% Processor Time", counters.cpuUsage, 1)); return metricsList; } }
I think ThreadDeath was removed intentionally in this repo ```suggestion ```
public void run() { try { while (!stopped) { long sleepInMillis; if (pingMode) { sleepInMillis = ping(); } else { sleepInMillis = sendData(); } Thread.sleep(sleepInMillis); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (ThreadDeath td) { throw td; } catch (Throwable t) { if (t instanceof Error) { throw (Error) t; } } }
throw td;
public void run() { try { while (!stopped) { long sleepInMillis; if (pingMode) { sleepInMillis = ping(); } else { sleepInMillis = sendData(); } Thread.sleep(sleepInMillis); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable t) { if (t instanceof Error) { throw (Error) t; } } }
class QuickPulseCoordinator implements Runnable { private static final ClientLogger logger = new ClientLogger(QuickPulseCoordinator.class); @Nullable private String qpsServiceRedirectedEndpoint; private long qpsServicePollingIntervalHintMillis; private volatile boolean stopped = false; private volatile boolean pingMode = true; private final QuickPulseDataCollector collector; private final QuickPulsePingSender pingSender; private final QuickPulseDataFetcher dataFetcher; private final QuickPulseDataSender dataSender; private final long waitBetweenPingsInMillis; private final long waitBetweenPostsInMillis; private final long waitOnErrorInMillis; QuickPulseCoordinator(QuickPulseCoordinatorInitData initData) { dataSender = initData.dataSender; pingSender = initData.pingSender; dataFetcher = initData.dataFetcher; collector = initData.collector; waitBetweenPingsInMillis = initData.waitBetweenPingsInMillis; waitBetweenPostsInMillis = initData.waitBetweenPostsInMillis; waitOnErrorInMillis = initData.waitOnErrorInMillis; qpsServiceRedirectedEndpoint = null; qpsServicePollingIntervalHintMillis = -1; } @Override @SuppressWarnings("try") private long sendData() { dataFetcher.prepareQuickPulseDataForSend(qpsServiceRedirectedEndpoint); QuickPulseHeaderInfo currentQuickPulseHeaderInfo = dataSender.getQuickPulseHeaderInfo(); this.handleReceivedHeaders(currentQuickPulseHeaderInfo); collector.setQuickPulseStatus(currentQuickPulseHeaderInfo.getQuickPulseStatus()); switch (currentQuickPulseHeaderInfo.getQuickPulseStatus()) { case ERROR: pingMode = true; return waitOnErrorInMillis; case QP_IS_OFF: pingMode = true; return qpsServicePollingIntervalHintMillis > 0 ? qpsServicePollingIntervalHintMillis : waitBetweenPingsInMillis; case QP_IS_ON: return waitBetweenPostsInMillis; } try (MDC.MDCCloseable ignored = QUICK_PULSE_SEND_ERROR.makeActive()) { logger.error("Critical error while sending QP data: unknown status, aborting"); } collector.disable(); stopped = true; return 0; } @SuppressWarnings("try") private long ping() { QuickPulseHeaderInfo pingResult = pingSender.ping(qpsServiceRedirectedEndpoint); this.handleReceivedHeaders(pingResult); collector.setQuickPulseStatus(pingResult.getQuickPulseStatus()); switch (pingResult.getQuickPulseStatus()) { case ERROR: return waitOnErrorInMillis; case QP_IS_ON: pingMode = false; dataSender.startSending(); return waitBetweenPostsInMillis; case QP_IS_OFF: return qpsServicePollingIntervalHintMillis > 0 ? qpsServicePollingIntervalHintMillis : waitBetweenPingsInMillis; } try (MDC.MDCCloseable ignored = QUICK_PULSE_PING_ERROR.makeActive()) { logger.error("Critical error while ping QP: unknown status, aborting"); } collector.disable(); stopped = true; return 0; } private void handleReceivedHeaders(QuickPulseHeaderInfo currentQuickPulseHeaderInfo) { String redirectLink = currentQuickPulseHeaderInfo.getQpsServiceEndpointRedirect(); if (!Strings.isNullOrEmpty(redirectLink)) { qpsServiceRedirectedEndpoint = redirectLink; } long newPollingInterval = currentQuickPulseHeaderInfo.getQpsServicePollingInterval(); if (newPollingInterval > 0) { qpsServicePollingIntervalHintMillis = newPollingInterval; } } void stop() { stopped = true; } }
class QuickPulseCoordinator implements Runnable { private static final ClientLogger logger = new ClientLogger(QuickPulseCoordinator.class); @Nullable private String qpsServiceRedirectedEndpoint; private long qpsServicePollingIntervalHintMillis; private volatile boolean stopped = false; private volatile boolean pingMode = true; private final QuickPulseDataCollector collector; private final QuickPulsePingSender pingSender; private final QuickPulseDataFetcher dataFetcher; private final QuickPulseDataSender dataSender; private final long waitBetweenPingsInMillis; private final long waitBetweenPostsInMillis; private final long waitOnErrorInMillis; QuickPulseCoordinator(QuickPulseCoordinatorInitData initData) { dataSender = initData.dataSender; pingSender = initData.pingSender; dataFetcher = initData.dataFetcher; collector = initData.collector; waitBetweenPingsInMillis = initData.waitBetweenPingsInMillis; waitBetweenPostsInMillis = initData.waitBetweenPostsInMillis; waitOnErrorInMillis = initData.waitOnErrorInMillis; qpsServiceRedirectedEndpoint = null; qpsServicePollingIntervalHintMillis = -1; } @Override @SuppressWarnings("try") private long sendData() { dataFetcher.prepareQuickPulseDataForSend(qpsServiceRedirectedEndpoint); QuickPulseHeaderInfo currentQuickPulseHeaderInfo = dataSender.getQuickPulseHeaderInfo(); this.handleReceivedHeaders(currentQuickPulseHeaderInfo); collector.setQuickPulseStatus(currentQuickPulseHeaderInfo.getQuickPulseStatus()); switch (currentQuickPulseHeaderInfo.getQuickPulseStatus()) { case ERROR: pingMode = true; return waitOnErrorInMillis; case QP_IS_OFF: pingMode = true; return qpsServicePollingIntervalHintMillis > 0 ? qpsServicePollingIntervalHintMillis : waitBetweenPingsInMillis; case QP_IS_ON: return waitBetweenPostsInMillis; } try (MDC.MDCCloseable ignored = QUICK_PULSE_SEND_ERROR.makeActive()) { logger.error("Critical error while sending QP data: unknown status, aborting"); } collector.disable(); stopped = true; return 0; } @SuppressWarnings("try") private long ping() { QuickPulseHeaderInfo pingResult = pingSender.ping(qpsServiceRedirectedEndpoint); this.handleReceivedHeaders(pingResult); collector.setQuickPulseStatus(pingResult.getQuickPulseStatus()); switch (pingResult.getQuickPulseStatus()) { case ERROR: return waitOnErrorInMillis; case QP_IS_ON: pingMode = false; dataSender.startSending(); return waitBetweenPostsInMillis; case QP_IS_OFF: return qpsServicePollingIntervalHintMillis > 0 ? qpsServicePollingIntervalHintMillis : waitBetweenPingsInMillis; } try (MDC.MDCCloseable ignored = QUICK_PULSE_PING_ERROR.makeActive()) { logger.error("Critical error while ping QP: unknown status, aborting"); } collector.disable(); stopped = true; return 0; } private void handleReceivedHeaders(QuickPulseHeaderInfo currentQuickPulseHeaderInfo) { String redirectLink = currentQuickPulseHeaderInfo.getQpsServiceEndpointRedirect(); if (!Strings.isNullOrEmpty(redirectLink)) { qpsServiceRedirectedEndpoint = redirectLink; } long newPollingInterval = currentQuickPulseHeaderInfo.getQpsServicePollingInterval(); if (newPollingInterval > 0) { qpsServicePollingIntervalHintMillis = newPollingInterval; } } void stop() { stopped = true; } }
```suggestion ```
public void prepareQuickPulseDataForSend(String redirectedEndpoint) { try { QuickPulseDataCollector.FinalCounters counters = collector.getAndRestart(); if (counters == null) { return; } Date currentDate = new Date(); String endpointPrefix = Strings.isNullOrEmpty(redirectedEndpoint) ? getQuickPulseEndpoint() : redirectedEndpoint; HttpRequest request = networkHelper.buildRequest(currentDate, this.getEndpointUrl(endpointPrefix)); request.setBody(buildPostEntity(counters)); if (!sendQueue.offer(request)) { logger.verbose("Quick Pulse send queue is full"); } } catch (ThreadDeath td) { throw td; } catch (Throwable e) { if (e instanceof Error) { throw (Error) e; } try { try (MDC.MDCCloseable ignored = QUICK_PULSE_SEND_ERROR.makeActive()) { logger.error("Quick Pulse failed to prepare data for send", e); } } catch (ThreadDeath td) { throw td; } catch (Throwable t2) { if (t2 instanceof Error) { throw (Error) t2; } } } }
throw td;
public void prepareQuickPulseDataForSend(String redirectedEndpoint) { try { QuickPulseDataCollector.FinalCounters counters = collector.getAndRestart(); if (counters == null) { return; } Date currentDate = new Date(); String endpointPrefix = Strings.isNullOrEmpty(redirectedEndpoint) ? getQuickPulseEndpoint() : redirectedEndpoint; HttpRequest request = networkHelper.buildRequest(currentDate, this.getEndpointUrl(endpointPrefix)); request.setBody(buildPostEntity(counters)); if (!sendQueue.offer(request)) { logger.verbose("Quick Pulse send queue is full"); } } catch (Throwable e) { if (e instanceof Error) { throw (Error) e; } try { try (MDC.MDCCloseable ignored = QUICK_PULSE_SEND_ERROR.makeActive()) { logger.error("Quick Pulse failed to prepare data for send", e); } } catch (Throwable t2) { if (t2 instanceof Error) { throw (Error) t2; } } } }
class QuickPulseDataFetcher { private static final ClientLogger logger = new ClientLogger(QuickPulseDataFetcher.class); private static final ObjectMapper mapper; static { mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.getFactory().setCharacterEscapes(new CustomCharacterEscapes()); } private final QuickPulseDataCollector collector; private final ArrayBlockingQueue<HttpRequest> sendQueue; private final QuickPulseNetworkHelper networkHelper = new QuickPulseNetworkHelper(); private final Supplier<URL> endpointUrl; private final Supplier<String> instrumentationKey; private final String roleName; private final String instanceName; private final String machineName; private final String quickPulseId; private final String sdkVersion; public QuickPulseDataFetcher( QuickPulseDataCollector collector, ArrayBlockingQueue<HttpRequest> sendQueue, Supplier<URL> endpointUrl, Supplier<String> instrumentationKey, String roleName, String instanceName, String machineName, String quickPulseId) { this.collector = collector; this.sendQueue = sendQueue; this.endpointUrl = endpointUrl; this.instrumentationKey = instrumentationKey; this.roleName = roleName; this.instanceName = instanceName; this.machineName = machineName; this.quickPulseId = quickPulseId; sdkVersion = getCurrentSdkVersion(); } /** * Returns SDK Version from properties. */ String getCurrentSdkVersion() { return "unknown"; } @SuppressWarnings("try") String getEndpointUrl(String endpointPrefix) { return endpointPrefix + "/post?ikey=" + instrumentationKey.get(); } String getQuickPulseEndpoint() { return endpointUrl.get().toString() + "QuickPulseService.svc"; } private String buildPostEntity(QuickPulseDataCollector.FinalCounters counters) throws JsonProcessingException { List<QuickPulseEnvelope> envelopes = new ArrayList<>(); QuickPulseEnvelope postEnvelope = new QuickPulseEnvelope(); postEnvelope.setDocuments(counters.documentList); postEnvelope.setInstance(instanceName); postEnvelope.setInvariantVersion(QuickPulse.QP_INVARIANT_VERSION); postEnvelope.setMachineName(machineName); postEnvelope.setRoleName(roleName); postEnvelope.setInstrumentationKey(instrumentationKey.get()); postEnvelope.setStreamId(quickPulseId); postEnvelope.setVersion(sdkVersion); postEnvelope.setTimeStamp("/Date(" + System.currentTimeMillis() + ")/"); postEnvelope.setMetrics(addMetricsToQuickPulseEnvelope(counters)); envelopes.add(postEnvelope); return mapper.writeValueAsString(envelopes); } private static List<QuickPulseMetrics> addMetricsToQuickPulseEnvelope( QuickPulseDataCollector.FinalCounters counters) { List<QuickPulseMetrics> metricsList = new ArrayList<>(); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Requests/Sec", counters.requests, 1)); if (counters.requests != 0) { metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Request Duration", counters.requestsDuration / counters.requests, counters.requests)); } metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Requests Failed/Sec", counters.unsuccessfulRequests, 1)); metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Requests Succeeded/Sec", counters.requests - counters.unsuccessfulRequests, 1)); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Dependency Calls/Sec", counters.rdds, 1)); if (counters.rdds != 0) { metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Call Duration", counters.rddsDuration / counters.rdds, (int) counters.rdds)); } metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Calls Failed/Sec", counters.unsuccessfulRdds, 1)); metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Calls Succeeded/Sec", counters.rdds - counters.unsuccessfulRdds, 1)); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Exceptions/Sec", counters.exceptions, 1)); metricsList.add( new QuickPulseMetrics("\\Memory\\Committed Bytes", counters.memoryCommitted, 1)); metricsList.add( new QuickPulseMetrics("\\Processor(_Total)\\% Processor Time", counters.cpuUsage, 1)); return metricsList; } }
class QuickPulseDataFetcher { private static final ClientLogger logger = new ClientLogger(QuickPulseDataFetcher.class); private static final ObjectMapper mapper; static { mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.getFactory().setCharacterEscapes(new CustomCharacterEscapes()); } private final QuickPulseDataCollector collector; private final ArrayBlockingQueue<HttpRequest> sendQueue; private final QuickPulseNetworkHelper networkHelper = new QuickPulseNetworkHelper(); private final Supplier<URL> endpointUrl; private final Supplier<String> instrumentationKey; private final String roleName; private final String instanceName; private final String machineName; private final String quickPulseId; private final String sdkVersion; public QuickPulseDataFetcher( QuickPulseDataCollector collector, ArrayBlockingQueue<HttpRequest> sendQueue, Supplier<URL> endpointUrl, Supplier<String> instrumentationKey, String roleName, String instanceName, String machineName, String quickPulseId) { this.collector = collector; this.sendQueue = sendQueue; this.endpointUrl = endpointUrl; this.instrumentationKey = instrumentationKey; this.roleName = roleName; this.instanceName = instanceName; this.machineName = machineName; this.quickPulseId = quickPulseId; sdkVersion = getCurrentSdkVersion(); } /** * Returns SDK Version from properties. */ String getCurrentSdkVersion() { return "unknown"; } @SuppressWarnings("try") String getEndpointUrl(String endpointPrefix) { return endpointPrefix + "/post?ikey=" + instrumentationKey.get(); } String getQuickPulseEndpoint() { return endpointUrl.get().toString() + "QuickPulseService.svc"; } private String buildPostEntity(QuickPulseDataCollector.FinalCounters counters) throws JsonProcessingException { List<QuickPulseEnvelope> envelopes = new ArrayList<>(); QuickPulseEnvelope postEnvelope = new QuickPulseEnvelope(); postEnvelope.setDocuments(counters.documentList); postEnvelope.setInstance(instanceName); postEnvelope.setInvariantVersion(QuickPulse.QP_INVARIANT_VERSION); postEnvelope.setMachineName(machineName); postEnvelope.setRoleName(roleName); postEnvelope.setInstrumentationKey(instrumentationKey.get()); postEnvelope.setStreamId(quickPulseId); postEnvelope.setVersion(sdkVersion); postEnvelope.setTimeStamp("/Date(" + System.currentTimeMillis() + ")/"); postEnvelope.setMetrics(addMetricsToQuickPulseEnvelope(counters)); envelopes.add(postEnvelope); return mapper.writeValueAsString(envelopes); } private static List<QuickPulseMetrics> addMetricsToQuickPulseEnvelope( QuickPulseDataCollector.FinalCounters counters) { List<QuickPulseMetrics> metricsList = new ArrayList<>(); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Requests/Sec", counters.requests, 1)); if (counters.requests != 0) { metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Request Duration", counters.requestsDuration / counters.requests, counters.requests)); } metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Requests Failed/Sec", counters.unsuccessfulRequests, 1)); metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Requests Succeeded/Sec", counters.requests - counters.unsuccessfulRequests, 1)); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Dependency Calls/Sec", counters.rdds, 1)); if (counters.rdds != 0) { metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Call Duration", counters.rddsDuration / counters.rdds, (int) counters.rdds)); } metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Calls Failed/Sec", counters.unsuccessfulRdds, 1)); metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Calls Succeeded/Sec", counters.rdds - counters.unsuccessfulRdds, 1)); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Exceptions/Sec", counters.exceptions, 1)); metricsList.add( new QuickPulseMetrics("\\Memory\\Committed Bytes", counters.memoryCommitted, 1)); metricsList.add( new QuickPulseMetrics("\\Processor(_Total)\\% Processor Time", counters.cpuUsage, 1)); return metricsList; } }
```suggestion ```
public void prepareQuickPulseDataForSend(String redirectedEndpoint) { try { QuickPulseDataCollector.FinalCounters counters = collector.getAndRestart(); if (counters == null) { return; } Date currentDate = new Date(); String endpointPrefix = Strings.isNullOrEmpty(redirectedEndpoint) ? getQuickPulseEndpoint() : redirectedEndpoint; HttpRequest request = networkHelper.buildRequest(currentDate, this.getEndpointUrl(endpointPrefix)); request.setBody(buildPostEntity(counters)); if (!sendQueue.offer(request)) { logger.verbose("Quick Pulse send queue is full"); } } catch (ThreadDeath td) { throw td; } catch (Throwable e) { if (e instanceof Error) { throw (Error) e; } try { try (MDC.MDCCloseable ignored = QUICK_PULSE_SEND_ERROR.makeActive()) { logger.error("Quick Pulse failed to prepare data for send", e); } } catch (ThreadDeath td) { throw td; } catch (Throwable t2) { if (t2 instanceof Error) { throw (Error) t2; } } } }
throw td;
public void prepareQuickPulseDataForSend(String redirectedEndpoint) { try { QuickPulseDataCollector.FinalCounters counters = collector.getAndRestart(); if (counters == null) { return; } Date currentDate = new Date(); String endpointPrefix = Strings.isNullOrEmpty(redirectedEndpoint) ? getQuickPulseEndpoint() : redirectedEndpoint; HttpRequest request = networkHelper.buildRequest(currentDate, this.getEndpointUrl(endpointPrefix)); request.setBody(buildPostEntity(counters)); if (!sendQueue.offer(request)) { logger.verbose("Quick Pulse send queue is full"); } } catch (Throwable e) { if (e instanceof Error) { throw (Error) e; } try { try (MDC.MDCCloseable ignored = QUICK_PULSE_SEND_ERROR.makeActive()) { logger.error("Quick Pulse failed to prepare data for send", e); } } catch (Throwable t2) { if (t2 instanceof Error) { throw (Error) t2; } } } }
class QuickPulseDataFetcher { private static final ClientLogger logger = new ClientLogger(QuickPulseDataFetcher.class); private static final ObjectMapper mapper; static { mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.getFactory().setCharacterEscapes(new CustomCharacterEscapes()); } private final QuickPulseDataCollector collector; private final ArrayBlockingQueue<HttpRequest> sendQueue; private final QuickPulseNetworkHelper networkHelper = new QuickPulseNetworkHelper(); private final Supplier<URL> endpointUrl; private final Supplier<String> instrumentationKey; private final String roleName; private final String instanceName; private final String machineName; private final String quickPulseId; private final String sdkVersion; public QuickPulseDataFetcher( QuickPulseDataCollector collector, ArrayBlockingQueue<HttpRequest> sendQueue, Supplier<URL> endpointUrl, Supplier<String> instrumentationKey, String roleName, String instanceName, String machineName, String quickPulseId) { this.collector = collector; this.sendQueue = sendQueue; this.endpointUrl = endpointUrl; this.instrumentationKey = instrumentationKey; this.roleName = roleName; this.instanceName = instanceName; this.machineName = machineName; this.quickPulseId = quickPulseId; sdkVersion = getCurrentSdkVersion(); } /** * Returns SDK Version from properties. */ String getCurrentSdkVersion() { return "unknown"; } @SuppressWarnings("try") String getEndpointUrl(String endpointPrefix) { return endpointPrefix + "/post?ikey=" + instrumentationKey.get(); } String getQuickPulseEndpoint() { return endpointUrl.get().toString() + "QuickPulseService.svc"; } private String buildPostEntity(QuickPulseDataCollector.FinalCounters counters) throws JsonProcessingException { List<QuickPulseEnvelope> envelopes = new ArrayList<>(); QuickPulseEnvelope postEnvelope = new QuickPulseEnvelope(); postEnvelope.setDocuments(counters.documentList); postEnvelope.setInstance(instanceName); postEnvelope.setInvariantVersion(QuickPulse.QP_INVARIANT_VERSION); postEnvelope.setMachineName(machineName); postEnvelope.setRoleName(roleName); postEnvelope.setInstrumentationKey(instrumentationKey.get()); postEnvelope.setStreamId(quickPulseId); postEnvelope.setVersion(sdkVersion); postEnvelope.setTimeStamp("/Date(" + System.currentTimeMillis() + ")/"); postEnvelope.setMetrics(addMetricsToQuickPulseEnvelope(counters)); envelopes.add(postEnvelope); return mapper.writeValueAsString(envelopes); } private static List<QuickPulseMetrics> addMetricsToQuickPulseEnvelope( QuickPulseDataCollector.FinalCounters counters) { List<QuickPulseMetrics> metricsList = new ArrayList<>(); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Requests/Sec", counters.requests, 1)); if (counters.requests != 0) { metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Request Duration", counters.requestsDuration / counters.requests, counters.requests)); } metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Requests Failed/Sec", counters.unsuccessfulRequests, 1)); metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Requests Succeeded/Sec", counters.requests - counters.unsuccessfulRequests, 1)); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Dependency Calls/Sec", counters.rdds, 1)); if (counters.rdds != 0) { metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Call Duration", counters.rddsDuration / counters.rdds, (int) counters.rdds)); } metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Calls Failed/Sec", counters.unsuccessfulRdds, 1)); metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Calls Succeeded/Sec", counters.rdds - counters.unsuccessfulRdds, 1)); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Exceptions/Sec", counters.exceptions, 1)); metricsList.add( new QuickPulseMetrics("\\Memory\\Committed Bytes", counters.memoryCommitted, 1)); metricsList.add( new QuickPulseMetrics("\\Processor(_Total)\\% Processor Time", counters.cpuUsage, 1)); return metricsList; } }
class QuickPulseDataFetcher { private static final ClientLogger logger = new ClientLogger(QuickPulseDataFetcher.class); private static final ObjectMapper mapper; static { mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.getFactory().setCharacterEscapes(new CustomCharacterEscapes()); } private final QuickPulseDataCollector collector; private final ArrayBlockingQueue<HttpRequest> sendQueue; private final QuickPulseNetworkHelper networkHelper = new QuickPulseNetworkHelper(); private final Supplier<URL> endpointUrl; private final Supplier<String> instrumentationKey; private final String roleName; private final String instanceName; private final String machineName; private final String quickPulseId; private final String sdkVersion; public QuickPulseDataFetcher( QuickPulseDataCollector collector, ArrayBlockingQueue<HttpRequest> sendQueue, Supplier<URL> endpointUrl, Supplier<String> instrumentationKey, String roleName, String instanceName, String machineName, String quickPulseId) { this.collector = collector; this.sendQueue = sendQueue; this.endpointUrl = endpointUrl; this.instrumentationKey = instrumentationKey; this.roleName = roleName; this.instanceName = instanceName; this.machineName = machineName; this.quickPulseId = quickPulseId; sdkVersion = getCurrentSdkVersion(); } /** * Returns SDK Version from properties. */ String getCurrentSdkVersion() { return "unknown"; } @SuppressWarnings("try") String getEndpointUrl(String endpointPrefix) { return endpointPrefix + "/post?ikey=" + instrumentationKey.get(); } String getQuickPulseEndpoint() { return endpointUrl.get().toString() + "QuickPulseService.svc"; } private String buildPostEntity(QuickPulseDataCollector.FinalCounters counters) throws JsonProcessingException { List<QuickPulseEnvelope> envelopes = new ArrayList<>(); QuickPulseEnvelope postEnvelope = new QuickPulseEnvelope(); postEnvelope.setDocuments(counters.documentList); postEnvelope.setInstance(instanceName); postEnvelope.setInvariantVersion(QuickPulse.QP_INVARIANT_VERSION); postEnvelope.setMachineName(machineName); postEnvelope.setRoleName(roleName); postEnvelope.setInstrumentationKey(instrumentationKey.get()); postEnvelope.setStreamId(quickPulseId); postEnvelope.setVersion(sdkVersion); postEnvelope.setTimeStamp("/Date(" + System.currentTimeMillis() + ")/"); postEnvelope.setMetrics(addMetricsToQuickPulseEnvelope(counters)); envelopes.add(postEnvelope); return mapper.writeValueAsString(envelopes); } private static List<QuickPulseMetrics> addMetricsToQuickPulseEnvelope( QuickPulseDataCollector.FinalCounters counters) { List<QuickPulseMetrics> metricsList = new ArrayList<>(); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Requests/Sec", counters.requests, 1)); if (counters.requests != 0) { metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Request Duration", counters.requestsDuration / counters.requests, counters.requests)); } metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Requests Failed/Sec", counters.unsuccessfulRequests, 1)); metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Requests Succeeded/Sec", counters.requests - counters.unsuccessfulRequests, 1)); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Dependency Calls/Sec", counters.rdds, 1)); if (counters.rdds != 0) { metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Call Duration", counters.rddsDuration / counters.rdds, (int) counters.rdds)); } metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Calls Failed/Sec", counters.unsuccessfulRdds, 1)); metricsList.add( new QuickPulseMetrics( "\\ApplicationInsights\\Dependency Calls Succeeded/Sec", counters.rdds - counters.unsuccessfulRdds, 1)); metricsList.add( new QuickPulseMetrics("\\ApplicationInsights\\Exceptions/Sec", counters.exceptions, 1)); metricsList.add( new QuickPulseMetrics("\\Memory\\Committed Bytes", counters.memoryCommitted, 1)); metricsList.add( new QuickPulseMetrics("\\Processor(_Total)\\% Processor Time", counters.cpuUsage, 1)); return metricsList; } }
This test was using gateway client for testing, why are we changing to direct mode? Also, this is not a good way to change it. A better way would be to actually change the dataProvider above. If you want to change to direct mode, then you can use this dataProvider - `clientBuildersWithDirectTcpSession`
public BulkExecutorTest(CosmosClientBuilder clientBuilder) { super(clientBuilder.directMode()); }
super(clientBuilder.directMode());
public BulkExecutorTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); }
class BulkExecutorTest extends BatchTestBase { private CosmosAsyncClient client; private CosmosAsyncContainer container; private CosmosAsyncDatabase database; private String preExistingDatabaseId = CosmosDatabaseForTest.generateId(); @Factory(dataProvider = "clientBuilders") @AfterClass(groups = { "emulator" }, timeOut = 3 * SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { logger.info("starting ...."); safeDeleteDatabase(database); safeClose(client); } @AfterMethod(groups = { "emulator" }) public void afterTest() throws Exception { if (this.container != null) { try { this.container.delete().block(); } catch (CosmosException error) { if (error.getStatusCode() != 404) { throw error; } } } } @BeforeMethod(groups = { "emulator" }) public void beforeTest() throws Exception { this.container = null; } @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void before_CosmosContainerTest() { client = getClientBuilder().buildAsyncClient(); database = createDatabase(client, preExistingDatabaseId); } static protected CosmosAsyncContainer createContainer(CosmosAsyncDatabase database) { String collectionName = UUID.randomUUID().toString(); CosmosContainerProperties containerProperties = getCollectionDefinition(collectionName); database.createContainer(containerProperties).block(); return database.getContainer(collectionName); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_cancel() throws InterruptedException { int totalRequest = 100; this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<CosmosItemOperation> inputFlux = Flux .fromArray(itemOperationsArray) .delayElements(Duration.ofMillis(100)); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( container, inputFlux, cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()).flatMap(response -> { logger.debug(String.valueOf(response.getResponse().getCosmosDiagnostics())); return Mono.just(response); });; Disposable disposable = bulkResponseFlux.subscribe(); disposable.dispose(); int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_OnConnectionDelayFailure() throws InterruptedException { this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); String duplicatePK = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(id, 2, 4, "type1", duplicatePK); CosmosItemOperation createOperation = (CosmosBulkOperations.getCreateItemOperation(id, eventDoc, new PartitionKey(duplicatePK))); cosmosItemOperations.add(createOperation); CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); FaultInjectionRule rule = injectFailure("ConnectionDelayed", this.container, FaultInjectionOperationType.BATCH_ITEM, FaultInjectionServerErrorType.CONNECTION_DELAY); Flux<CosmosItemOperation> inputFlux = Flux .fromArray(itemOperationsArray) .delayElements(Duration.ofMillis(100)); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( this.container, inputFlux, cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()); Mono<List<CosmosBulkOperationResponse<BulkExecutorTest>>> convertToListMono = bulkResponseFlux .collect(Collectors.toList()); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = convertToListMono.block(); assertThat(bulkResponse.size()).isEqualTo(1); CosmosBulkOperationResponse<BulkExecutorTest> operationResponse = bulkResponse.get(0); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = operationResponse.getResponse(); assertThat(cosmosBulkItemResponse).isNull(); int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } rule.disable(); } private FaultInjectionRule injectFailure(String id, CosmosAsyncContainer createdContainer, FaultInjectionOperationType operationType, FaultInjectionServerErrorType serverErrorType) { FaultInjectionServerErrorResultBuilder faultInjectionResultBuilder = FaultInjectionResultBuilders .getResultBuilder(serverErrorType) .delay(Duration.ofMillis(1500)) .times(1); IFaultInjectionResult result = faultInjectionResultBuilder.build(); FaultInjectionCondition condition = new FaultInjectionConditionBuilder() .operationType(operationType) .connectionType(FaultInjectionConnectionType.DIRECT) .build(); FaultInjectionRule rule = new FaultInjectionRuleBuilder(id) .condition(condition) .result(result) .startDelay(Duration.ofSeconds(1)) .hitLimit(1) .build(); FaultInjectorProvider injectorProvider = (FaultInjectorProvider) ImplementationBridgeHelpers.CosmosAsyncContainerHelper .getCosmosAsyncContainerAccessor() .getOrConfigureFaultInjectorProvider(createdContainer, () -> new FaultInjectorProvider(createdContainer)); injectorProvider.configureFaultInjectionRules(Arrays.asList(rule)).block(); return rule; } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_complete() throws InterruptedException { int totalRequest = 10; this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( container, Flux.fromArray(itemOperationsArray), cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()); Mono<List<CosmosBulkOperationResponse<BulkExecutorTest>>> convertToListMono = bulkResponseFlux .collect(Collectors.toList()); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = convertToListMono.block(); assertThat(bulkResponse.size()).isEqualTo(totalRequest * 2); for (com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest> cosmosBulkOperationResponse : bulkResponse) { com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); } int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } } }
class BulkExecutorTest extends BatchTestBase { private CosmosAsyncClient client; private CosmosAsyncContainer container; private CosmosAsyncDatabase database; private String preExistingDatabaseId = CosmosDatabaseForTest.generateId(); @Factory(dataProvider = "simpleClientBuildersWithJustDirectTcp") @AfterClass(groups = { "emulator" }, timeOut = 3 * SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { logger.info("starting ...."); safeDeleteDatabase(database); safeClose(client); } @AfterMethod(groups = { "emulator" }) public void afterTest() throws Exception { if (this.container != null) { try { this.container.delete().block(); } catch (CosmosException error) { if (error.getStatusCode() != 404) { throw error; } } } } @BeforeMethod(groups = { "emulator" }) public void beforeTest() throws Exception { this.container = null; } @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void before_CosmosContainerTest() { client = getClientBuilder().buildAsyncClient(); database = createDatabase(client, preExistingDatabaseId); } static protected CosmosAsyncContainer createContainer(CosmosAsyncDatabase database) { String collectionName = UUID.randomUUID().toString(); CosmosContainerProperties containerProperties = getCollectionDefinition(collectionName); database.createContainer(containerProperties).block(); return database.getContainer(collectionName); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_cancel() throws InterruptedException { int totalRequest = 100; this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<CosmosItemOperation> inputFlux = Flux .fromArray(itemOperationsArray) .delayElements(Duration.ofMillis(100)); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( container, inputFlux, cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()); Disposable disposable = bulkResponseFlux.subscribe(); disposable.dispose(); int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_OnGoneFailure() throws InterruptedException { this.container = createContainer(database); if (!ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getConnectionMode(this.client) .equals(ConnectionMode.DIRECT.toString())) { throw new SkipException("Failure injection for gone exception only supported for DIRECT mode"); } List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); String duplicatePK = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(id, 2, 4, "type1", duplicatePK); CosmosItemOperation createOperation = (CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(duplicatePK))); cosmosItemOperations.add(createOperation); FaultInjectionRule connectionCloseRule = new FaultInjectionRuleBuilder("connectionClose-" + UUID.randomUUID()) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.BATCH_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionConnectionErrorType.CONNECTION_CLOSE) .interval(Duration.ofMillis(200)) .build() ) .duration(Duration.ofSeconds(10)) .build(); FaultInjectionRule serverResponseDelayRule = new FaultInjectionRuleBuilder("serverResponseDelay-" + UUID.randomUUID()) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.BATCH_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.RESPONSE_DELAY) .delay(Duration.ofSeconds(1)) .build() ) .duration(Duration.ofSeconds(10)) .build(); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( this.container, Flux.fromIterable(cosmosItemOperations), new CosmosBulkExecutionOptions()); try { CosmosFaultInjectionHelper .configureFaultInjectionRules(container, Arrays.asList(connectionCloseRule, serverResponseDelayRule)) .block(); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = Flux .deferContextual(context -> executor.execute()) .collectList() .block(); assertThat(bulkResponse.size()).isEqualTo(1); CosmosBulkOperationResponse<BulkExecutorTest> operationResponse = bulkResponse.get(0); CosmosBulkItemResponse cosmosBulkItemResponse = operationResponse.getResponse(); assertThat(cosmosBulkItemResponse).isNull(); } finally { if (executor != null && !executor.isDisposed()) { executor.dispose(); } connectionCloseRule.disable(); serverResponseDelayRule.disable(); } } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_complete() throws InterruptedException { int totalRequest = 10; this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( container, Flux.fromArray(itemOperationsArray), cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()); Mono<List<CosmosBulkOperationResponse<BulkExecutorTest>>> convertToListMono = bulkResponseFlux .collect(Collectors.toList()); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = convertToListMono.block(); assertThat(bulkResponse.size()).isEqualTo(totalRequest * 2); for (com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest> cosmosBulkOperationResponse : bulkResponse) { com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); } int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } } }
Do we need this log?
public void executeBulk_cancel() throws InterruptedException { int totalRequest = 100; this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<CosmosItemOperation> inputFlux = Flux .fromArray(itemOperationsArray) .delayElements(Duration.ofMillis(100)); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( container, inputFlux, cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()).flatMap(response -> { logger.debug(String.valueOf(response.getResponse().getCosmosDiagnostics())); return Mono.just(response); });; Disposable disposable = bulkResponseFlux.subscribe(); disposable.dispose(); int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } }
logger.debug(String.valueOf(response.getResponse().getCosmosDiagnostics()));
public void executeBulk_cancel() throws InterruptedException { int totalRequest = 100; this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<CosmosItemOperation> inputFlux = Flux .fromArray(itemOperationsArray) .delayElements(Duration.ofMillis(100)); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( container, inputFlux, cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()); Disposable disposable = bulkResponseFlux.subscribe(); disposable.dispose(); int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } }
class BulkExecutorTest extends BatchTestBase { private CosmosAsyncClient client; private CosmosAsyncContainer container; private CosmosAsyncDatabase database; private String preExistingDatabaseId = CosmosDatabaseForTest.generateId(); @Factory(dataProvider = "clientBuilders") public BulkExecutorTest(CosmosClientBuilder clientBuilder) { super(clientBuilder.directMode()); } @AfterClass(groups = { "emulator" }, timeOut = 3 * SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { logger.info("starting ...."); safeDeleteDatabase(database); safeClose(client); } @AfterMethod(groups = { "emulator" }) public void afterTest() throws Exception { if (this.container != null) { try { this.container.delete().block(); } catch (CosmosException error) { if (error.getStatusCode() != 404) { throw error; } } } } @BeforeMethod(groups = { "emulator" }) public void beforeTest() throws Exception { this.container = null; } @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void before_CosmosContainerTest() { client = getClientBuilder().buildAsyncClient(); database = createDatabase(client, preExistingDatabaseId); } static protected CosmosAsyncContainer createContainer(CosmosAsyncDatabase database) { String collectionName = UUID.randomUUID().toString(); CosmosContainerProperties containerProperties = getCollectionDefinition(collectionName); database.createContainer(containerProperties).block(); return database.getContainer(collectionName); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_OnConnectionDelayFailure() throws InterruptedException { this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); String duplicatePK = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(id, 2, 4, "type1", duplicatePK); CosmosItemOperation createOperation = (CosmosBulkOperations.getCreateItemOperation(id, eventDoc, new PartitionKey(duplicatePK))); cosmosItemOperations.add(createOperation); CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); FaultInjectionRule rule = injectFailure("ConnectionDelayed", this.container, FaultInjectionOperationType.BATCH_ITEM, FaultInjectionServerErrorType.CONNECTION_DELAY); Flux<CosmosItemOperation> inputFlux = Flux .fromArray(itemOperationsArray) .delayElements(Duration.ofMillis(100)); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( this.container, inputFlux, cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()); Mono<List<CosmosBulkOperationResponse<BulkExecutorTest>>> convertToListMono = bulkResponseFlux .collect(Collectors.toList()); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = convertToListMono.block(); assertThat(bulkResponse.size()).isEqualTo(1); CosmosBulkOperationResponse<BulkExecutorTest> operationResponse = bulkResponse.get(0); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = operationResponse.getResponse(); assertThat(cosmosBulkItemResponse).isNull(); int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } rule.disable(); } private FaultInjectionRule injectFailure(String id, CosmosAsyncContainer createdContainer, FaultInjectionOperationType operationType, FaultInjectionServerErrorType serverErrorType) { FaultInjectionServerErrorResultBuilder faultInjectionResultBuilder = FaultInjectionResultBuilders .getResultBuilder(serverErrorType) .delay(Duration.ofMillis(1500)) .times(1); IFaultInjectionResult result = faultInjectionResultBuilder.build(); FaultInjectionCondition condition = new FaultInjectionConditionBuilder() .operationType(operationType) .connectionType(FaultInjectionConnectionType.DIRECT) .build(); FaultInjectionRule rule = new FaultInjectionRuleBuilder(id) .condition(condition) .result(result) .startDelay(Duration.ofSeconds(1)) .hitLimit(1) .build(); FaultInjectorProvider injectorProvider = (FaultInjectorProvider) ImplementationBridgeHelpers.CosmosAsyncContainerHelper .getCosmosAsyncContainerAccessor() .getOrConfigureFaultInjectorProvider(createdContainer, () -> new FaultInjectorProvider(createdContainer)); injectorProvider.configureFaultInjectionRules(Arrays.asList(rule)).block(); return rule; } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_complete() throws InterruptedException { int totalRequest = 10; this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( container, Flux.fromArray(itemOperationsArray), cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()); Mono<List<CosmosBulkOperationResponse<BulkExecutorTest>>> convertToListMono = bulkResponseFlux .collect(Collectors.toList()); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = convertToListMono.block(); assertThat(bulkResponse.size()).isEqualTo(totalRequest * 2); for (com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest> cosmosBulkOperationResponse : bulkResponse) { com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); } int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } } }
class BulkExecutorTest extends BatchTestBase { private CosmosAsyncClient client; private CosmosAsyncContainer container; private CosmosAsyncDatabase database; private String preExistingDatabaseId = CosmosDatabaseForTest.generateId(); @Factory(dataProvider = "simpleClientBuildersWithJustDirectTcp") public BulkExecutorTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @AfterClass(groups = { "emulator" }, timeOut = 3 * SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { logger.info("starting ...."); safeDeleteDatabase(database); safeClose(client); } @AfterMethod(groups = { "emulator" }) public void afterTest() throws Exception { if (this.container != null) { try { this.container.delete().block(); } catch (CosmosException error) { if (error.getStatusCode() != 404) { throw error; } } } } @BeforeMethod(groups = { "emulator" }) public void beforeTest() throws Exception { this.container = null; } @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void before_CosmosContainerTest() { client = getClientBuilder().buildAsyncClient(); database = createDatabase(client, preExistingDatabaseId); } static protected CosmosAsyncContainer createContainer(CosmosAsyncDatabase database) { String collectionName = UUID.randomUUID().toString(); CosmosContainerProperties containerProperties = getCollectionDefinition(collectionName); database.createContainer(containerProperties).block(); return database.getContainer(collectionName); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_OnGoneFailure() throws InterruptedException { this.container = createContainer(database); if (!ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getConnectionMode(this.client) .equals(ConnectionMode.DIRECT.toString())) { throw new SkipException("Failure injection for gone exception only supported for DIRECT mode"); } List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); String duplicatePK = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(id, 2, 4, "type1", duplicatePK); CosmosItemOperation createOperation = (CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(duplicatePK))); cosmosItemOperations.add(createOperation); FaultInjectionRule connectionCloseRule = new FaultInjectionRuleBuilder("connectionClose-" + UUID.randomUUID()) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.BATCH_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionConnectionErrorType.CONNECTION_CLOSE) .interval(Duration.ofMillis(200)) .build() ) .duration(Duration.ofSeconds(10)) .build(); FaultInjectionRule serverResponseDelayRule = new FaultInjectionRuleBuilder("serverResponseDelay-" + UUID.randomUUID()) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.BATCH_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.RESPONSE_DELAY) .delay(Duration.ofSeconds(1)) .build() ) .duration(Duration.ofSeconds(10)) .build(); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( this.container, Flux.fromIterable(cosmosItemOperations), new CosmosBulkExecutionOptions()); try { CosmosFaultInjectionHelper .configureFaultInjectionRules(container, Arrays.asList(connectionCloseRule, serverResponseDelayRule)) .block(); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = Flux .deferContextual(context -> executor.execute()) .collectList() .block(); assertThat(bulkResponse.size()).isEqualTo(1); CosmosBulkOperationResponse<BulkExecutorTest> operationResponse = bulkResponse.get(0); CosmosBulkItemResponse cosmosBulkItemResponse = operationResponse.getResponse(); assertThat(cosmosBulkItemResponse).isNull(); } finally { if (executor != null && !executor.isDisposed()) { executor.dispose(); } connectionCloseRule.disable(); serverResponseDelayRule.disable(); } } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_complete() throws InterruptedException { int totalRequest = 10; this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( container, Flux.fromArray(itemOperationsArray), cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()); Mono<List<CosmosBulkOperationResponse<BulkExecutorTest>>> convertToListMono = bulkResponseFlux .collect(Collectors.toList()); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = convertToListMono.block(); assertThat(bulkResponse.size()).isEqualTo(totalRequest * 2); for (com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest> cosmosBulkOperationResponse : bulkResponse) { com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); } int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } } }
Changed it to `simpleClientBuildersWithJustDirectTcp` because the gone exception fault injection only works with direct.
public BulkExecutorTest(CosmosClientBuilder clientBuilder) { super(clientBuilder.directMode()); }
super(clientBuilder.directMode());
public BulkExecutorTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); }
class BulkExecutorTest extends BatchTestBase { private CosmosAsyncClient client; private CosmosAsyncContainer container; private CosmosAsyncDatabase database; private String preExistingDatabaseId = CosmosDatabaseForTest.generateId(); @Factory(dataProvider = "clientBuilders") @AfterClass(groups = { "emulator" }, timeOut = 3 * SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { logger.info("starting ...."); safeDeleteDatabase(database); safeClose(client); } @AfterMethod(groups = { "emulator" }) public void afterTest() throws Exception { if (this.container != null) { try { this.container.delete().block(); } catch (CosmosException error) { if (error.getStatusCode() != 404) { throw error; } } } } @BeforeMethod(groups = { "emulator" }) public void beforeTest() throws Exception { this.container = null; } @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void before_CosmosContainerTest() { client = getClientBuilder().buildAsyncClient(); database = createDatabase(client, preExistingDatabaseId); } static protected CosmosAsyncContainer createContainer(CosmosAsyncDatabase database) { String collectionName = UUID.randomUUID().toString(); CosmosContainerProperties containerProperties = getCollectionDefinition(collectionName); database.createContainer(containerProperties).block(); return database.getContainer(collectionName); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_cancel() throws InterruptedException { int totalRequest = 100; this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<CosmosItemOperation> inputFlux = Flux .fromArray(itemOperationsArray) .delayElements(Duration.ofMillis(100)); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( container, inputFlux, cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()).flatMap(response -> { logger.debug(String.valueOf(response.getResponse().getCosmosDiagnostics())); return Mono.just(response); });; Disposable disposable = bulkResponseFlux.subscribe(); disposable.dispose(); int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_OnConnectionDelayFailure() throws InterruptedException { this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); String duplicatePK = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(id, 2, 4, "type1", duplicatePK); CosmosItemOperation createOperation = (CosmosBulkOperations.getCreateItemOperation(id, eventDoc, new PartitionKey(duplicatePK))); cosmosItemOperations.add(createOperation); CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); FaultInjectionRule rule = injectFailure("ConnectionDelayed", this.container, FaultInjectionOperationType.BATCH_ITEM, FaultInjectionServerErrorType.CONNECTION_DELAY); Flux<CosmosItemOperation> inputFlux = Flux .fromArray(itemOperationsArray) .delayElements(Duration.ofMillis(100)); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( this.container, inputFlux, cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()); Mono<List<CosmosBulkOperationResponse<BulkExecutorTest>>> convertToListMono = bulkResponseFlux .collect(Collectors.toList()); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = convertToListMono.block(); assertThat(bulkResponse.size()).isEqualTo(1); CosmosBulkOperationResponse<BulkExecutorTest> operationResponse = bulkResponse.get(0); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = operationResponse.getResponse(); assertThat(cosmosBulkItemResponse).isNull(); int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } rule.disable(); } private FaultInjectionRule injectFailure(String id, CosmosAsyncContainer createdContainer, FaultInjectionOperationType operationType, FaultInjectionServerErrorType serverErrorType) { FaultInjectionServerErrorResultBuilder faultInjectionResultBuilder = FaultInjectionResultBuilders .getResultBuilder(serverErrorType) .delay(Duration.ofMillis(1500)) .times(1); IFaultInjectionResult result = faultInjectionResultBuilder.build(); FaultInjectionCondition condition = new FaultInjectionConditionBuilder() .operationType(operationType) .connectionType(FaultInjectionConnectionType.DIRECT) .build(); FaultInjectionRule rule = new FaultInjectionRuleBuilder(id) .condition(condition) .result(result) .startDelay(Duration.ofSeconds(1)) .hitLimit(1) .build(); FaultInjectorProvider injectorProvider = (FaultInjectorProvider) ImplementationBridgeHelpers.CosmosAsyncContainerHelper .getCosmosAsyncContainerAccessor() .getOrConfigureFaultInjectorProvider(createdContainer, () -> new FaultInjectorProvider(createdContainer)); injectorProvider.configureFaultInjectionRules(Arrays.asList(rule)).block(); return rule; } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_complete() throws InterruptedException { int totalRequest = 10; this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( container, Flux.fromArray(itemOperationsArray), cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()); Mono<List<CosmosBulkOperationResponse<BulkExecutorTest>>> convertToListMono = bulkResponseFlux .collect(Collectors.toList()); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = convertToListMono.block(); assertThat(bulkResponse.size()).isEqualTo(totalRequest * 2); for (com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest> cosmosBulkOperationResponse : bulkResponse) { com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); } int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } } }
class BulkExecutorTest extends BatchTestBase { private CosmosAsyncClient client; private CosmosAsyncContainer container; private CosmosAsyncDatabase database; private String preExistingDatabaseId = CosmosDatabaseForTest.generateId(); @Factory(dataProvider = "simpleClientBuildersWithJustDirectTcp") @AfterClass(groups = { "emulator" }, timeOut = 3 * SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { logger.info("starting ...."); safeDeleteDatabase(database); safeClose(client); } @AfterMethod(groups = { "emulator" }) public void afterTest() throws Exception { if (this.container != null) { try { this.container.delete().block(); } catch (CosmosException error) { if (error.getStatusCode() != 404) { throw error; } } } } @BeforeMethod(groups = { "emulator" }) public void beforeTest() throws Exception { this.container = null; } @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void before_CosmosContainerTest() { client = getClientBuilder().buildAsyncClient(); database = createDatabase(client, preExistingDatabaseId); } static protected CosmosAsyncContainer createContainer(CosmosAsyncDatabase database) { String collectionName = UUID.randomUUID().toString(); CosmosContainerProperties containerProperties = getCollectionDefinition(collectionName); database.createContainer(containerProperties).block(); return database.getContainer(collectionName); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_cancel() throws InterruptedException { int totalRequest = 100; this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<CosmosItemOperation> inputFlux = Flux .fromArray(itemOperationsArray) .delayElements(Duration.ofMillis(100)); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( container, inputFlux, cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()); Disposable disposable = bulkResponseFlux.subscribe(); disposable.dispose(); int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_OnGoneFailure() throws InterruptedException { this.container = createContainer(database); if (!ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getConnectionMode(this.client) .equals(ConnectionMode.DIRECT.toString())) { throw new SkipException("Failure injection for gone exception only supported for DIRECT mode"); } List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); String duplicatePK = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(id, 2, 4, "type1", duplicatePK); CosmosItemOperation createOperation = (CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(duplicatePK))); cosmosItemOperations.add(createOperation); FaultInjectionRule connectionCloseRule = new FaultInjectionRuleBuilder("connectionClose-" + UUID.randomUUID()) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.BATCH_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionConnectionErrorType.CONNECTION_CLOSE) .interval(Duration.ofMillis(200)) .build() ) .duration(Duration.ofSeconds(10)) .build(); FaultInjectionRule serverResponseDelayRule = new FaultInjectionRuleBuilder("serverResponseDelay-" + UUID.randomUUID()) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.BATCH_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.RESPONSE_DELAY) .delay(Duration.ofSeconds(1)) .build() ) .duration(Duration.ofSeconds(10)) .build(); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( this.container, Flux.fromIterable(cosmosItemOperations), new CosmosBulkExecutionOptions()); try { CosmosFaultInjectionHelper .configureFaultInjectionRules(container, Arrays.asList(connectionCloseRule, serverResponseDelayRule)) .block(); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = Flux .deferContextual(context -> executor.execute()) .collectList() .block(); assertThat(bulkResponse.size()).isEqualTo(1); CosmosBulkOperationResponse<BulkExecutorTest> operationResponse = bulkResponse.get(0); CosmosBulkItemResponse cosmosBulkItemResponse = operationResponse.getResponse(); assertThat(cosmosBulkItemResponse).isNull(); } finally { if (executor != null && !executor.isDisposed()) { executor.dispose(); } connectionCloseRule.disable(); serverResponseDelayRule.disable(); } } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_complete() throws InterruptedException { int totalRequest = 10; this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( container, Flux.fromArray(itemOperationsArray), cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()); Mono<List<CosmosBulkOperationResponse<BulkExecutorTest>>> convertToListMono = bulkResponseFlux .collect(Collectors.toList()); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = convertToListMono.block(); assertThat(bulkResponse.size()).isEqualTo(totalRequest * 2); for (com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest> cosmosBulkOperationResponse : bulkResponse) { com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); } int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } } }
removed log
public void executeBulk_cancel() throws InterruptedException { int totalRequest = 100; this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<CosmosItemOperation> inputFlux = Flux .fromArray(itemOperationsArray) .delayElements(Duration.ofMillis(100)); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( container, inputFlux, cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()).flatMap(response -> { logger.debug(String.valueOf(response.getResponse().getCosmosDiagnostics())); return Mono.just(response); });; Disposable disposable = bulkResponseFlux.subscribe(); disposable.dispose(); int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } }
logger.debug(String.valueOf(response.getResponse().getCosmosDiagnostics()));
public void executeBulk_cancel() throws InterruptedException { int totalRequest = 100; this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); Flux<CosmosItemOperation> inputFlux = Flux .fromArray(itemOperationsArray) .delayElements(Duration.ofMillis(100)); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( container, inputFlux, cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()); Disposable disposable = bulkResponseFlux.subscribe(); disposable.dispose(); int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } }
class BulkExecutorTest extends BatchTestBase { private CosmosAsyncClient client; private CosmosAsyncContainer container; private CosmosAsyncDatabase database; private String preExistingDatabaseId = CosmosDatabaseForTest.generateId(); @Factory(dataProvider = "clientBuilders") public BulkExecutorTest(CosmosClientBuilder clientBuilder) { super(clientBuilder.directMode()); } @AfterClass(groups = { "emulator" }, timeOut = 3 * SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { logger.info("starting ...."); safeDeleteDatabase(database); safeClose(client); } @AfterMethod(groups = { "emulator" }) public void afterTest() throws Exception { if (this.container != null) { try { this.container.delete().block(); } catch (CosmosException error) { if (error.getStatusCode() != 404) { throw error; } } } } @BeforeMethod(groups = { "emulator" }) public void beforeTest() throws Exception { this.container = null; } @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void before_CosmosContainerTest() { client = getClientBuilder().buildAsyncClient(); database = createDatabase(client, preExistingDatabaseId); } static protected CosmosAsyncContainer createContainer(CosmosAsyncDatabase database) { String collectionName = UUID.randomUUID().toString(); CosmosContainerProperties containerProperties = getCollectionDefinition(collectionName); database.createContainer(containerProperties).block(); return database.getContainer(collectionName); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_OnConnectionDelayFailure() throws InterruptedException { this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); String duplicatePK = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(id, 2, 4, "type1", duplicatePK); CosmosItemOperation createOperation = (CosmosBulkOperations.getCreateItemOperation(id, eventDoc, new PartitionKey(duplicatePK))); cosmosItemOperations.add(createOperation); CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); FaultInjectionRule rule = injectFailure("ConnectionDelayed", this.container, FaultInjectionOperationType.BATCH_ITEM, FaultInjectionServerErrorType.CONNECTION_DELAY); Flux<CosmosItemOperation> inputFlux = Flux .fromArray(itemOperationsArray) .delayElements(Duration.ofMillis(100)); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( this.container, inputFlux, cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()); Mono<List<CosmosBulkOperationResponse<BulkExecutorTest>>> convertToListMono = bulkResponseFlux .collect(Collectors.toList()); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = convertToListMono.block(); assertThat(bulkResponse.size()).isEqualTo(1); CosmosBulkOperationResponse<BulkExecutorTest> operationResponse = bulkResponse.get(0); com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = operationResponse.getResponse(); assertThat(cosmosBulkItemResponse).isNull(); int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } rule.disable(); } private FaultInjectionRule injectFailure(String id, CosmosAsyncContainer createdContainer, FaultInjectionOperationType operationType, FaultInjectionServerErrorType serverErrorType) { FaultInjectionServerErrorResultBuilder faultInjectionResultBuilder = FaultInjectionResultBuilders .getResultBuilder(serverErrorType) .delay(Duration.ofMillis(1500)) .times(1); IFaultInjectionResult result = faultInjectionResultBuilder.build(); FaultInjectionCondition condition = new FaultInjectionConditionBuilder() .operationType(operationType) .connectionType(FaultInjectionConnectionType.DIRECT) .build(); FaultInjectionRule rule = new FaultInjectionRuleBuilder(id) .condition(condition) .result(result) .startDelay(Duration.ofSeconds(1)) .hitLimit(1) .build(); FaultInjectorProvider injectorProvider = (FaultInjectorProvider) ImplementationBridgeHelpers.CosmosAsyncContainerHelper .getCosmosAsyncContainerAccessor() .getOrConfigureFaultInjectorProvider(createdContainer, () -> new FaultInjectorProvider(createdContainer)); injectorProvider.configureFaultInjectionRules(Arrays.asList(rule)).block(); return rule; } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_complete() throws InterruptedException { int totalRequest = 10; this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( container, Flux.fromArray(itemOperationsArray), cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()); Mono<List<CosmosBulkOperationResponse<BulkExecutorTest>>> convertToListMono = bulkResponseFlux .collect(Collectors.toList()); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = convertToListMono.block(); assertThat(bulkResponse.size()).isEqualTo(totalRequest * 2); for (com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest> cosmosBulkOperationResponse : bulkResponse) { com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); } int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } } }
class BulkExecutorTest extends BatchTestBase { private CosmosAsyncClient client; private CosmosAsyncContainer container; private CosmosAsyncDatabase database; private String preExistingDatabaseId = CosmosDatabaseForTest.generateId(); @Factory(dataProvider = "simpleClientBuildersWithJustDirectTcp") public BulkExecutorTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @AfterClass(groups = { "emulator" }, timeOut = 3 * SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { logger.info("starting ...."); safeDeleteDatabase(database); safeClose(client); } @AfterMethod(groups = { "emulator" }) public void afterTest() throws Exception { if (this.container != null) { try { this.container.delete().block(); } catch (CosmosException error) { if (error.getStatusCode() != 404) { throw error; } } } } @BeforeMethod(groups = { "emulator" }) public void beforeTest() throws Exception { this.container = null; } @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void before_CosmosContainerTest() { client = getClientBuilder().buildAsyncClient(); database = createDatabase(client, preExistingDatabaseId); } static protected CosmosAsyncContainer createContainer(CosmosAsyncDatabase database) { String collectionName = UUID.randomUUID().toString(); CosmosContainerProperties containerProperties = getCollectionDefinition(collectionName); database.createContainer(containerProperties).block(); return database.getContainer(collectionName); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_OnGoneFailure() throws InterruptedException { this.container = createContainer(database); if (!ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getConnectionMode(this.client) .equals(ConnectionMode.DIRECT.toString())) { throw new SkipException("Failure injection for gone exception only supported for DIRECT mode"); } List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); String duplicatePK = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(id, 2, 4, "type1", duplicatePK); CosmosItemOperation createOperation = (CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(duplicatePK))); cosmosItemOperations.add(createOperation); FaultInjectionRule connectionCloseRule = new FaultInjectionRuleBuilder("connectionClose-" + UUID.randomUUID()) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.BATCH_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionConnectionErrorType.CONNECTION_CLOSE) .interval(Duration.ofMillis(200)) .build() ) .duration(Duration.ofSeconds(10)) .build(); FaultInjectionRule serverResponseDelayRule = new FaultInjectionRuleBuilder("serverResponseDelay-" + UUID.randomUUID()) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.BATCH_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.RESPONSE_DELAY) .delay(Duration.ofSeconds(1)) .build() ) .duration(Duration.ofSeconds(10)) .build(); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( this.container, Flux.fromIterable(cosmosItemOperations), new CosmosBulkExecutionOptions()); try { CosmosFaultInjectionHelper .configureFaultInjectionRules(container, Arrays.asList(connectionCloseRule, serverResponseDelayRule)) .block(); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = Flux .deferContextual(context -> executor.execute()) .collectList() .block(); assertThat(bulkResponse.size()).isEqualTo(1); CosmosBulkOperationResponse<BulkExecutorTest> operationResponse = bulkResponse.get(0); CosmosBulkItemResponse cosmosBulkItemResponse = operationResponse.getResponse(); assertThat(cosmosBulkItemResponse).isNull(); } finally { if (executor != null && !executor.isDisposed()) { executor.dispose(); } connectionCloseRule.disable(); serverResponseDelayRule.disable(); } } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void executeBulk_complete() throws InterruptedException { int totalRequest = 10; this.container = createContainer(database); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosItemOperation[] itemOperationsArray = new CosmosItemOperation[cosmosItemOperations.size()]; cosmosItemOperations.toArray(itemOperationsArray); CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); final BulkExecutor<BulkExecutorTest> executor = new BulkExecutor<>( container, Flux.fromArray(itemOperationsArray), cosmosBulkExecutionOptions); Flux<com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponseFlux = Flux.deferContextual(context -> executor.execute()); Mono<List<CosmosBulkOperationResponse<BulkExecutorTest>>> convertToListMono = bulkResponseFlux .collect(Collectors.toList()); List<CosmosBulkOperationResponse<BulkExecutorTest>> bulkResponse = convertToListMono.block(); assertThat(bulkResponse.size()).isEqualTo(totalRequest * 2); for (com.azure.cosmos.models.CosmosBulkOperationResponse<BulkExecutorTest> cosmosBulkOperationResponse : bulkResponse) { com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); } int iterations = 0; while (true) { assertThat(iterations < 100); if (executor.isDisposed()) { break; } Thread.sleep(10); iterations++; } } }
Should this be moved to somewhere else? I don't see a need in creating the default HTTP client if the test mode is PLAYBACK.
protected void beforeTest() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .connectionString(TestUtils.getConnectionString()) .retryOptions(TestUtils.getRetryOptions()) .httpClient(HttpClient.createDefault()) .hub(TestUtils.HUB_NAME); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())); } else if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } this.client = builder.buildAsyncClient(); }
.httpClient(HttpClient.createDefault())
protected void beforeTest() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .connectionString(TestUtils.getConnectionString()) .retryOptions(TestUtils.getRetryOptions()) .hub(TestUtils.HUB_NAME); switch (getTestMode()) { case LIVE: builder.httpClient(HttpClient.createDefault()); break; case RECORD: builder.httpClient(HttpClient.createDefault()) .addPolicy(interceptorManager.getRecordPolicy()); break; case PLAYBACK: builder.httpClient(interceptorManager.getPlaybackClient()); break; default: throw new IllegalStateException("Unknown test mode. " + getTestMode()); } this.client = builder.buildAsyncClient(); }
class WebPubSubServiceAsyncClientTests extends TestProxyTestBase { private static final Duration TIMEOUT = Duration.ofSeconds(10); private static final String USER_ID = "test_user"; private static final RequestOptions REQUEST_OPTIONS_TEXT = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain"); }); private static final RequestOptions REQUEST_OPTIONS_STREAM = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/octet-stream"); }); private static final BinaryData MESSAGE = BinaryData.fromString("Hello World - Broadcast test!"); private WebPubSubServiceAsyncClient client; @Override private static void assertResponse(Mono<Response<Void>> operation) { StepVerifier.create(operation) .assertNext(response -> { assertNotNull(response); assertEquals(202, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testBroadcastString() { assertResponse(client.sendToAllWithResponse(MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testBroadcastStringWithFilter() { RequestOptions requestOptions = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToAllWithResponse(MESSAGE, requestOptions)); } @Test public void testBroadcastBytes() { byte[] bytes = "Hello World - Broadcast test!".getBytes(); assertResponse(client.sendToAllWithResponse(BinaryData.fromBytes(bytes), REQUEST_OPTIONS_STREAM)); } @Test public void testSendToUserString() throws IOException { assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), null)); } } @Test public void testSendToUserStringWithFilter() throws IOException { RequestOptions requestOptions = new RequestOptions() .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), requestOptions)); } } @Test public void testSendToUserBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToUserWithResponse(USER_ID, binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionString() { assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testSendToConnectionStringWithFilter() { final RequestOptions filter = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, filter)); } @Test public void testSendToConnectionBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToConnectionWithResponse("test_connection", binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromString("{\"data\": true}"), requestOptions)); } @Test public void testSendToAllJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"boolvalue\": true}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"stringvalue\": \"testingwebpubsub\"}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"intvalue\": 25}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"floatvalue\": 55.4}"), requestOptions)); } @Test public void testRemoveNonExistentUserFromHub() { StepVerifier.create(client.removeUserFromAllGroupsWithResponse("testRemoveNonExistentUserFromHub", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveConnectionFromAllGroup() { StepVerifier.create(client.removeConnectionFromAllGroupsWithResponse("test_connection", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test @DoNotRecord(skipInPlayback = true) public void testGetAuthenticationToken() { StepVerifier.create(client.getClientAccessToken(new GetClientAccessTokenOptions())) .assertNext(token -> { Assertions.assertNotNull(token); Assertions.assertNotNull(token.getToken()); Assertions.assertNotNull(token.getUrl()); assertTrue(token.getUrl().startsWith("wss: assertTrue(token.getUrl().contains(".webpubsub.azure.com/client/hubs/")); String authToken = token.getToken(); JWT jwt; try { jwt = JWTParser.parse(authToken); } catch (ParseException e) { fail("Unable to parse auth token: " + authToken + " exception: ", e); return; } JWTClaimsSet claimsSet; try { claimsSet = jwt.getJWTClaimsSet(); } catch (ParseException e) { fail("Unable to parse claims: " + authToken + " exception: ", e); return; } assertNotNull(claimsSet); assertNotNull(claimsSet.getAudience()); assertFalse(claimsSet.getAudience().isEmpty()); String aud = claimsSet.getAudience().iterator().next(); assertTrue(aud.contains(".webpubsub.azure.com/client/hubs/")); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveNonExistentUserFromGroup() { StepVerifier.create(client.removeUserFromGroupWithResponse("java", "testRemoveNonExistentUserFromGroup", new RequestOptions()), 204); } @Test public void testSendMessageToGroup() { StepVerifier.create(client.sendToGroupWithResponse("java", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain"))), 202); } @Test public void testAadCredential() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .endpoint(TestUtils.getEndpoint()) .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .hub("test"); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())) .connectionString(TestUtils.getConnectionString()); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } final WebPubSubServiceAsyncClient asyncClient = builder.buildAsyncClient(); assertResponse(asyncClient.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testCheckPermission() { assumeTrue(getTestMode() == TestMode.PLAYBACK, "This requires real " + "connection id that is created when a client connects to Web PubSub service. So, run this in PLAYBACK " + "mode only."); RequestOptions requestOptions = new RequestOptions() .addQueryParam("targetName", "java"); StepVerifier.create(client.checkPermissionWithResponse(WebPubSubPermission.SEND_TO_GROUP, "71xtjgThROOJ6DsVY3xbBw2ef45fd11", requestOptions)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); assertTrue(response.getValue()); }) .expectComplete() .verify(TIMEOUT); } }
class WebPubSubServiceAsyncClientTests extends TestProxyTestBase { private static final Duration TIMEOUT = Duration.ofSeconds(10); private static final String USER_ID = "test_user"; private static final RequestOptions REQUEST_OPTIONS_TEXT = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain"); }); private static final RequestOptions REQUEST_OPTIONS_STREAM = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/octet-stream"); }); private static final BinaryData MESSAGE = BinaryData.fromString("Hello World - Broadcast test!"); private WebPubSubServiceAsyncClient client; @Override private static void assertResponse(Mono<Response<Void>> operation) { StepVerifier.create(operation) .assertNext(response -> { assertNotNull(response); assertEquals(202, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testBroadcastString() { assertResponse(client.sendToAllWithResponse(MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testBroadcastStringWithFilter() { RequestOptions requestOptions = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToAllWithResponse(MESSAGE, requestOptions)); } @Test public void testBroadcastBytes() { byte[] bytes = "Hello World - Broadcast test!".getBytes(); assertResponse(client.sendToAllWithResponse(BinaryData.fromBytes(bytes), REQUEST_OPTIONS_STREAM)); } @Test public void testSendToUserString() throws IOException { assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), null)); } } @Test public void testSendToUserStringWithFilter() throws IOException { RequestOptions requestOptions = new RequestOptions() .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), requestOptions)); } } @Test public void testSendToUserBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToUserWithResponse(USER_ID, binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionString() { assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testSendToConnectionStringWithFilter() { final RequestOptions filter = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, filter)); } @Test public void testSendToConnectionBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToConnectionWithResponse("test_connection", binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromString("{\"data\": true}"), requestOptions)); } @Test public void testSendToAllJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"boolvalue\": true}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"stringvalue\": \"testingwebpubsub\"}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"intvalue\": 25}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"floatvalue\": 55.4}"), requestOptions)); } @Test public void testRemoveNonExistentUserFromHub() { StepVerifier.create(client.removeUserFromAllGroupsWithResponse("testRemoveNonExistentUserFromHub", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveConnectionFromAllGroup() { StepVerifier.create(client.removeConnectionFromAllGroupsWithResponse("test_connection", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test @DoNotRecord(skipInPlayback = true) public void testGetAuthenticationToken() { StepVerifier.create(client.getClientAccessToken(new GetClientAccessTokenOptions())) .assertNext(token -> { Assertions.assertNotNull(token); Assertions.assertNotNull(token.getToken()); Assertions.assertNotNull(token.getUrl()); assertTrue(token.getUrl().startsWith("wss: assertTrue(token.getUrl().contains(".webpubsub.azure.com/client/hubs/")); String authToken = token.getToken(); JWT jwt; try { jwt = JWTParser.parse(authToken); } catch (ParseException e) { fail("Unable to parse auth token: " + authToken + " exception: ", e); return; } JWTClaimsSet claimsSet; try { claimsSet = jwt.getJWTClaimsSet(); } catch (ParseException e) { fail("Unable to parse claims: " + authToken + " exception: ", e); return; } assertNotNull(claimsSet); assertNotNull(claimsSet.getAudience()); assertFalse(claimsSet.getAudience().isEmpty()); String aud = claimsSet.getAudience().iterator().next(); assertTrue(aud.contains(".webpubsub.azure.com/client/hubs/")); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveNonExistentUserFromGroup() { StepVerifier.create(client.removeUserFromGroupWithResponse("java", "testRemoveNonExistentUserFromGroup", new RequestOptions()), 204); } @Test public void testSendMessageToGroup() { StepVerifier.create(client.sendToGroupWithResponse("java", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain"))), 202); } @Test public void testAadCredential() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .endpoint(TestUtils.getEndpoint()) .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .hub("test"); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())) .connectionString(TestUtils.getConnectionString()); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } final WebPubSubServiceAsyncClient asyncClient = builder.buildAsyncClient(); assertResponse(asyncClient.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testCheckPermission() { assumeTrue(getTestMode() == TestMode.PLAYBACK, "This requires real " + "connection id that is created when a client connects to Web PubSub service. So, run this in PLAYBACK " + "mode only."); RequestOptions requestOptions = new RequestOptions() .addQueryParam("targetName", "java"); StepVerifier.create(client.checkPermissionWithResponse(WebPubSubPermission.SEND_TO_GROUP, "71xtjgThROOJ6DsVY3xbBw2ef45fd11", requestOptions)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); assertTrue(response.getValue()); }) .expectComplete() .verify(TIMEOUT); } }
Why are we using a retry policy with no retries?
protected void beforeTest() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .connectionString(TestUtils.getConnectionString()) .retryOptions(TestUtils.getRetryOptions()) .httpClient(HttpClient.createDefault()) .hub(TestUtils.HUB_NAME); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())); } else if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } this.client = builder.buildAsyncClient(); }
.retryOptions(TestUtils.getRetryOptions())
protected void beforeTest() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .connectionString(TestUtils.getConnectionString()) .retryOptions(TestUtils.getRetryOptions()) .hub(TestUtils.HUB_NAME); switch (getTestMode()) { case LIVE: builder.httpClient(HttpClient.createDefault()); break; case RECORD: builder.httpClient(HttpClient.createDefault()) .addPolicy(interceptorManager.getRecordPolicy()); break; case PLAYBACK: builder.httpClient(interceptorManager.getPlaybackClient()); break; default: throw new IllegalStateException("Unknown test mode. " + getTestMode()); } this.client = builder.buildAsyncClient(); }
class WebPubSubServiceAsyncClientTests extends TestProxyTestBase { private static final Duration TIMEOUT = Duration.ofSeconds(10); private static final String USER_ID = "test_user"; private static final RequestOptions REQUEST_OPTIONS_TEXT = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain"); }); private static final RequestOptions REQUEST_OPTIONS_STREAM = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/octet-stream"); }); private static final BinaryData MESSAGE = BinaryData.fromString("Hello World - Broadcast test!"); private WebPubSubServiceAsyncClient client; @Override private static void assertResponse(Mono<Response<Void>> operation) { StepVerifier.create(operation) .assertNext(response -> { assertNotNull(response); assertEquals(202, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testBroadcastString() { assertResponse(client.sendToAllWithResponse(MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testBroadcastStringWithFilter() { RequestOptions requestOptions = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToAllWithResponse(MESSAGE, requestOptions)); } @Test public void testBroadcastBytes() { byte[] bytes = "Hello World - Broadcast test!".getBytes(); assertResponse(client.sendToAllWithResponse(BinaryData.fromBytes(bytes), REQUEST_OPTIONS_STREAM)); } @Test public void testSendToUserString() throws IOException { assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), null)); } } @Test public void testSendToUserStringWithFilter() throws IOException { RequestOptions requestOptions = new RequestOptions() .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), requestOptions)); } } @Test public void testSendToUserBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToUserWithResponse(USER_ID, binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionString() { assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testSendToConnectionStringWithFilter() { final RequestOptions filter = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, filter)); } @Test public void testSendToConnectionBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToConnectionWithResponse("test_connection", binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromString("{\"data\": true}"), requestOptions)); } @Test public void testSendToAllJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"boolvalue\": true}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"stringvalue\": \"testingwebpubsub\"}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"intvalue\": 25}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"floatvalue\": 55.4}"), requestOptions)); } @Test public void testRemoveNonExistentUserFromHub() { StepVerifier.create(client.removeUserFromAllGroupsWithResponse("testRemoveNonExistentUserFromHub", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveConnectionFromAllGroup() { StepVerifier.create(client.removeConnectionFromAllGroupsWithResponse("test_connection", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test @DoNotRecord(skipInPlayback = true) public void testGetAuthenticationToken() { StepVerifier.create(client.getClientAccessToken(new GetClientAccessTokenOptions())) .assertNext(token -> { Assertions.assertNotNull(token); Assertions.assertNotNull(token.getToken()); Assertions.assertNotNull(token.getUrl()); assertTrue(token.getUrl().startsWith("wss: assertTrue(token.getUrl().contains(".webpubsub.azure.com/client/hubs/")); String authToken = token.getToken(); JWT jwt; try { jwt = JWTParser.parse(authToken); } catch (ParseException e) { fail("Unable to parse auth token: " + authToken + " exception: ", e); return; } JWTClaimsSet claimsSet; try { claimsSet = jwt.getJWTClaimsSet(); } catch (ParseException e) { fail("Unable to parse claims: " + authToken + " exception: ", e); return; } assertNotNull(claimsSet); assertNotNull(claimsSet.getAudience()); assertFalse(claimsSet.getAudience().isEmpty()); String aud = claimsSet.getAudience().iterator().next(); assertTrue(aud.contains(".webpubsub.azure.com/client/hubs/")); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveNonExistentUserFromGroup() { StepVerifier.create(client.removeUserFromGroupWithResponse("java", "testRemoveNonExistentUserFromGroup", new RequestOptions()), 204); } @Test public void testSendMessageToGroup() { StepVerifier.create(client.sendToGroupWithResponse("java", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain"))), 202); } @Test public void testAadCredential() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .endpoint(TestUtils.getEndpoint()) .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .hub("test"); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())) .connectionString(TestUtils.getConnectionString()); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } final WebPubSubServiceAsyncClient asyncClient = builder.buildAsyncClient(); assertResponse(asyncClient.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testCheckPermission() { assumeTrue(getTestMode() == TestMode.PLAYBACK, "This requires real " + "connection id that is created when a client connects to Web PubSub service. So, run this in PLAYBACK " + "mode only."); RequestOptions requestOptions = new RequestOptions() .addQueryParam("targetName", "java"); StepVerifier.create(client.checkPermissionWithResponse(WebPubSubPermission.SEND_TO_GROUP, "71xtjgThROOJ6DsVY3xbBw2ef45fd11", requestOptions)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); assertTrue(response.getValue()); }) .expectComplete() .verify(TIMEOUT); } }
class WebPubSubServiceAsyncClientTests extends TestProxyTestBase { private static final Duration TIMEOUT = Duration.ofSeconds(10); private static final String USER_ID = "test_user"; private static final RequestOptions REQUEST_OPTIONS_TEXT = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain"); }); private static final RequestOptions REQUEST_OPTIONS_STREAM = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/octet-stream"); }); private static final BinaryData MESSAGE = BinaryData.fromString("Hello World - Broadcast test!"); private WebPubSubServiceAsyncClient client; @Override private static void assertResponse(Mono<Response<Void>> operation) { StepVerifier.create(operation) .assertNext(response -> { assertNotNull(response); assertEquals(202, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testBroadcastString() { assertResponse(client.sendToAllWithResponse(MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testBroadcastStringWithFilter() { RequestOptions requestOptions = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToAllWithResponse(MESSAGE, requestOptions)); } @Test public void testBroadcastBytes() { byte[] bytes = "Hello World - Broadcast test!".getBytes(); assertResponse(client.sendToAllWithResponse(BinaryData.fromBytes(bytes), REQUEST_OPTIONS_STREAM)); } @Test public void testSendToUserString() throws IOException { assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), null)); } } @Test public void testSendToUserStringWithFilter() throws IOException { RequestOptions requestOptions = new RequestOptions() .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), requestOptions)); } } @Test public void testSendToUserBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToUserWithResponse(USER_ID, binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionString() { assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testSendToConnectionStringWithFilter() { final RequestOptions filter = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, filter)); } @Test public void testSendToConnectionBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToConnectionWithResponse("test_connection", binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromString("{\"data\": true}"), requestOptions)); } @Test public void testSendToAllJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"boolvalue\": true}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"stringvalue\": \"testingwebpubsub\"}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"intvalue\": 25}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"floatvalue\": 55.4}"), requestOptions)); } @Test public void testRemoveNonExistentUserFromHub() { StepVerifier.create(client.removeUserFromAllGroupsWithResponse("testRemoveNonExistentUserFromHub", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveConnectionFromAllGroup() { StepVerifier.create(client.removeConnectionFromAllGroupsWithResponse("test_connection", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test @DoNotRecord(skipInPlayback = true) public void testGetAuthenticationToken() { StepVerifier.create(client.getClientAccessToken(new GetClientAccessTokenOptions())) .assertNext(token -> { Assertions.assertNotNull(token); Assertions.assertNotNull(token.getToken()); Assertions.assertNotNull(token.getUrl()); assertTrue(token.getUrl().startsWith("wss: assertTrue(token.getUrl().contains(".webpubsub.azure.com/client/hubs/")); String authToken = token.getToken(); JWT jwt; try { jwt = JWTParser.parse(authToken); } catch (ParseException e) { fail("Unable to parse auth token: " + authToken + " exception: ", e); return; } JWTClaimsSet claimsSet; try { claimsSet = jwt.getJWTClaimsSet(); } catch (ParseException e) { fail("Unable to parse claims: " + authToken + " exception: ", e); return; } assertNotNull(claimsSet); assertNotNull(claimsSet.getAudience()); assertFalse(claimsSet.getAudience().isEmpty()); String aud = claimsSet.getAudience().iterator().next(); assertTrue(aud.contains(".webpubsub.azure.com/client/hubs/")); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveNonExistentUserFromGroup() { StepVerifier.create(client.removeUserFromGroupWithResponse("java", "testRemoveNonExistentUserFromGroup", new RequestOptions()), 204); } @Test public void testSendMessageToGroup() { StepVerifier.create(client.sendToGroupWithResponse("java", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain"))), 202); } @Test public void testAadCredential() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .endpoint(TestUtils.getEndpoint()) .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .hub("test"); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())) .connectionString(TestUtils.getConnectionString()); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } final WebPubSubServiceAsyncClient asyncClient = builder.buildAsyncClient(); assertResponse(asyncClient.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testCheckPermission() { assumeTrue(getTestMode() == TestMode.PLAYBACK, "This requires real " + "connection id that is created when a client connects to Web PubSub service. So, run this in PLAYBACK " + "mode only."); RequestOptions requestOptions = new RequestOptions() .addQueryParam("targetName", "java"); StepVerifier.create(client.checkPermissionWithResponse(WebPubSubPermission.SEND_TO_GROUP, "71xtjgThROOJ6DsVY3xbBw2ef45fd11", requestOptions)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); assertTrue(response.getValue()); }) .expectComplete() .verify(TIMEOUT); } }
Does this test mutate the bytes being sent? Why do we turn a BinaryData into an InputStream then to turn it back into a BinaryData? Same goes for the few other tests using this same pattern.
public void testSendToUserString() throws IOException { assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), null)); } }
try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) {
public void testSendToUserString() throws IOException { assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), null)); } }
class WebPubSubServiceAsyncClientTests extends TestProxyTestBase { private static final Duration TIMEOUT = Duration.ofSeconds(10); private static final String USER_ID = "test_user"; private static final RequestOptions REQUEST_OPTIONS_TEXT = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain"); }); private static final RequestOptions REQUEST_OPTIONS_STREAM = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/octet-stream"); }); private static final BinaryData MESSAGE = BinaryData.fromString("Hello World - Broadcast test!"); private WebPubSubServiceAsyncClient client; @Override protected void beforeTest() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .connectionString(TestUtils.getConnectionString()) .retryOptions(TestUtils.getRetryOptions()) .httpClient(HttpClient.createDefault()) .hub(TestUtils.HUB_NAME); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())); } else if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } this.client = builder.buildAsyncClient(); } private static void assertResponse(Mono<Response<Void>> operation) { StepVerifier.create(operation) .assertNext(response -> { assertNotNull(response); assertEquals(202, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testBroadcastString() { assertResponse(client.sendToAllWithResponse(MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testBroadcastStringWithFilter() { RequestOptions requestOptions = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToAllWithResponse(MESSAGE, requestOptions)); } @Test public void testBroadcastBytes() { byte[] bytes = "Hello World - Broadcast test!".getBytes(); assertResponse(client.sendToAllWithResponse(BinaryData.fromBytes(bytes), REQUEST_OPTIONS_STREAM)); } @Test @Test public void testSendToUserStringWithFilter() throws IOException { RequestOptions requestOptions = new RequestOptions() .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), requestOptions)); } } @Test public void testSendToUserBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToUserWithResponse(USER_ID, binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionString() { assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testSendToConnectionStringWithFilter() { final RequestOptions filter = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, filter)); } @Test public void testSendToConnectionBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToConnectionWithResponse("test_connection", binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromString("{\"data\": true}"), requestOptions)); } @Test public void testSendToAllJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"boolvalue\": true}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"stringvalue\": \"testingwebpubsub\"}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"intvalue\": 25}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"floatvalue\": 55.4}"), requestOptions)); } @Test public void testRemoveNonExistentUserFromHub() { StepVerifier.create(client.removeUserFromAllGroupsWithResponse("testRemoveNonExistentUserFromHub", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveConnectionFromAllGroup() { StepVerifier.create(client.removeConnectionFromAllGroupsWithResponse("test_connection", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test @DoNotRecord(skipInPlayback = true) public void testGetAuthenticationToken() { StepVerifier.create(client.getClientAccessToken(new GetClientAccessTokenOptions())) .assertNext(token -> { Assertions.assertNotNull(token); Assertions.assertNotNull(token.getToken()); Assertions.assertNotNull(token.getUrl()); assertTrue(token.getUrl().startsWith("wss: assertTrue(token.getUrl().contains(".webpubsub.azure.com/client/hubs/")); String authToken = token.getToken(); JWT jwt; try { jwt = JWTParser.parse(authToken); } catch (ParseException e) { fail("Unable to parse auth token: " + authToken + " exception: ", e); return; } JWTClaimsSet claimsSet; try { claimsSet = jwt.getJWTClaimsSet(); } catch (ParseException e) { fail("Unable to parse claims: " + authToken + " exception: ", e); return; } assertNotNull(claimsSet); assertNotNull(claimsSet.getAudience()); assertFalse(claimsSet.getAudience().isEmpty()); String aud = claimsSet.getAudience().iterator().next(); assertTrue(aud.contains(".webpubsub.azure.com/client/hubs/")); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveNonExistentUserFromGroup() { StepVerifier.create(client.removeUserFromGroupWithResponse("java", "testRemoveNonExistentUserFromGroup", new RequestOptions()), 204); } @Test public void testSendMessageToGroup() { StepVerifier.create(client.sendToGroupWithResponse("java", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain"))), 202); } @Test public void testAadCredential() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .endpoint(TestUtils.getEndpoint()) .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .hub("test"); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())) .connectionString(TestUtils.getConnectionString()); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } final WebPubSubServiceAsyncClient asyncClient = builder.buildAsyncClient(); assertResponse(asyncClient.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testCheckPermission() { assumeTrue(getTestMode() == TestMode.PLAYBACK, "This requires real " + "connection id that is created when a client connects to Web PubSub service. So, run this in PLAYBACK " + "mode only."); RequestOptions requestOptions = new RequestOptions() .addQueryParam("targetName", "java"); StepVerifier.create(client.checkPermissionWithResponse(WebPubSubPermission.SEND_TO_GROUP, "71xtjgThROOJ6DsVY3xbBw2ef45fd11", requestOptions)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); assertTrue(response.getValue()); }) .expectComplete() .verify(TIMEOUT); } }
class WebPubSubServiceAsyncClientTests extends TestProxyTestBase { private static final Duration TIMEOUT = Duration.ofSeconds(10); private static final String USER_ID = "test_user"; private static final RequestOptions REQUEST_OPTIONS_TEXT = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain"); }); private static final RequestOptions REQUEST_OPTIONS_STREAM = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/octet-stream"); }); private static final BinaryData MESSAGE = BinaryData.fromString("Hello World - Broadcast test!"); private WebPubSubServiceAsyncClient client; @Override protected void beforeTest() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .connectionString(TestUtils.getConnectionString()) .retryOptions(TestUtils.getRetryOptions()) .hub(TestUtils.HUB_NAME); switch (getTestMode()) { case LIVE: builder.httpClient(HttpClient.createDefault()); break; case RECORD: builder.httpClient(HttpClient.createDefault()) .addPolicy(interceptorManager.getRecordPolicy()); break; case PLAYBACK: builder.httpClient(interceptorManager.getPlaybackClient()); break; default: throw new IllegalStateException("Unknown test mode. " + getTestMode()); } this.client = builder.buildAsyncClient(); } private static void assertResponse(Mono<Response<Void>> operation) { StepVerifier.create(operation) .assertNext(response -> { assertNotNull(response); assertEquals(202, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testBroadcastString() { assertResponse(client.sendToAllWithResponse(MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testBroadcastStringWithFilter() { RequestOptions requestOptions = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToAllWithResponse(MESSAGE, requestOptions)); } @Test public void testBroadcastBytes() { byte[] bytes = "Hello World - Broadcast test!".getBytes(); assertResponse(client.sendToAllWithResponse(BinaryData.fromBytes(bytes), REQUEST_OPTIONS_STREAM)); } @Test @Test public void testSendToUserStringWithFilter() throws IOException { RequestOptions requestOptions = new RequestOptions() .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), requestOptions)); } } @Test public void testSendToUserBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToUserWithResponse(USER_ID, binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionString() { assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testSendToConnectionStringWithFilter() { final RequestOptions filter = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, filter)); } @Test public void testSendToConnectionBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToConnectionWithResponse("test_connection", binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromString("{\"data\": true}"), requestOptions)); } @Test public void testSendToAllJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"boolvalue\": true}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"stringvalue\": \"testingwebpubsub\"}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"intvalue\": 25}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"floatvalue\": 55.4}"), requestOptions)); } @Test public void testRemoveNonExistentUserFromHub() { StepVerifier.create(client.removeUserFromAllGroupsWithResponse("testRemoveNonExistentUserFromHub", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveConnectionFromAllGroup() { StepVerifier.create(client.removeConnectionFromAllGroupsWithResponse("test_connection", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test @DoNotRecord(skipInPlayback = true) public void testGetAuthenticationToken() { StepVerifier.create(client.getClientAccessToken(new GetClientAccessTokenOptions())) .assertNext(token -> { Assertions.assertNotNull(token); Assertions.assertNotNull(token.getToken()); Assertions.assertNotNull(token.getUrl()); assertTrue(token.getUrl().startsWith("wss: assertTrue(token.getUrl().contains(".webpubsub.azure.com/client/hubs/")); String authToken = token.getToken(); JWT jwt; try { jwt = JWTParser.parse(authToken); } catch (ParseException e) { fail("Unable to parse auth token: " + authToken + " exception: ", e); return; } JWTClaimsSet claimsSet; try { claimsSet = jwt.getJWTClaimsSet(); } catch (ParseException e) { fail("Unable to parse claims: " + authToken + " exception: ", e); return; } assertNotNull(claimsSet); assertNotNull(claimsSet.getAudience()); assertFalse(claimsSet.getAudience().isEmpty()); String aud = claimsSet.getAudience().iterator().next(); assertTrue(aud.contains(".webpubsub.azure.com/client/hubs/")); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveNonExistentUserFromGroup() { StepVerifier.create(client.removeUserFromGroupWithResponse("java", "testRemoveNonExistentUserFromGroup", new RequestOptions()), 204); } @Test public void testSendMessageToGroup() { StepVerifier.create(client.sendToGroupWithResponse("java", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain"))), 202); } @Test public void testAadCredential() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .endpoint(TestUtils.getEndpoint()) .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .hub("test"); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())) .connectionString(TestUtils.getConnectionString()); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } final WebPubSubServiceAsyncClient asyncClient = builder.buildAsyncClient(); assertResponse(asyncClient.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testCheckPermission() { assumeTrue(getTestMode() == TestMode.PLAYBACK, "This requires real " + "connection id that is created when a client connects to Web PubSub service. So, run this in PLAYBACK " + "mode only."); RequestOptions requestOptions = new RequestOptions() .addQueryParam("targetName", "java"); StepVerifier.create(client.checkPermissionWithResponse(WebPubSubPermission.SEND_TO_GROUP, "71xtjgThROOJ6DsVY3xbBw2ef45fd11", requestOptions)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); assertTrue(response.getValue()); }) .expectComplete() .verify(TIMEOUT); } }
Yeah. I think it was to make the conditional chains smaller in logic when it was first written.
protected void beforeTest() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .connectionString(TestUtils.getConnectionString()) .retryOptions(TestUtils.getRetryOptions()) .httpClient(HttpClient.createDefault()) .hub(TestUtils.HUB_NAME); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())); } else if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } this.client = builder.buildAsyncClient(); }
.httpClient(HttpClient.createDefault())
protected void beforeTest() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .connectionString(TestUtils.getConnectionString()) .retryOptions(TestUtils.getRetryOptions()) .hub(TestUtils.HUB_NAME); switch (getTestMode()) { case LIVE: builder.httpClient(HttpClient.createDefault()); break; case RECORD: builder.httpClient(HttpClient.createDefault()) .addPolicy(interceptorManager.getRecordPolicy()); break; case PLAYBACK: builder.httpClient(interceptorManager.getPlaybackClient()); break; default: throw new IllegalStateException("Unknown test mode. " + getTestMode()); } this.client = builder.buildAsyncClient(); }
class WebPubSubServiceAsyncClientTests extends TestProxyTestBase { private static final Duration TIMEOUT = Duration.ofSeconds(10); private static final String USER_ID = "test_user"; private static final RequestOptions REQUEST_OPTIONS_TEXT = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain"); }); private static final RequestOptions REQUEST_OPTIONS_STREAM = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/octet-stream"); }); private static final BinaryData MESSAGE = BinaryData.fromString("Hello World - Broadcast test!"); private WebPubSubServiceAsyncClient client; @Override private static void assertResponse(Mono<Response<Void>> operation) { StepVerifier.create(operation) .assertNext(response -> { assertNotNull(response); assertEquals(202, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testBroadcastString() { assertResponse(client.sendToAllWithResponse(MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testBroadcastStringWithFilter() { RequestOptions requestOptions = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToAllWithResponse(MESSAGE, requestOptions)); } @Test public void testBroadcastBytes() { byte[] bytes = "Hello World - Broadcast test!".getBytes(); assertResponse(client.sendToAllWithResponse(BinaryData.fromBytes(bytes), REQUEST_OPTIONS_STREAM)); } @Test public void testSendToUserString() throws IOException { assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), null)); } } @Test public void testSendToUserStringWithFilter() throws IOException { RequestOptions requestOptions = new RequestOptions() .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), requestOptions)); } } @Test public void testSendToUserBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToUserWithResponse(USER_ID, binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionString() { assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testSendToConnectionStringWithFilter() { final RequestOptions filter = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, filter)); } @Test public void testSendToConnectionBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToConnectionWithResponse("test_connection", binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromString("{\"data\": true}"), requestOptions)); } @Test public void testSendToAllJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"boolvalue\": true}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"stringvalue\": \"testingwebpubsub\"}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"intvalue\": 25}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"floatvalue\": 55.4}"), requestOptions)); } @Test public void testRemoveNonExistentUserFromHub() { StepVerifier.create(client.removeUserFromAllGroupsWithResponse("testRemoveNonExistentUserFromHub", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveConnectionFromAllGroup() { StepVerifier.create(client.removeConnectionFromAllGroupsWithResponse("test_connection", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test @DoNotRecord(skipInPlayback = true) public void testGetAuthenticationToken() { StepVerifier.create(client.getClientAccessToken(new GetClientAccessTokenOptions())) .assertNext(token -> { Assertions.assertNotNull(token); Assertions.assertNotNull(token.getToken()); Assertions.assertNotNull(token.getUrl()); assertTrue(token.getUrl().startsWith("wss: assertTrue(token.getUrl().contains(".webpubsub.azure.com/client/hubs/")); String authToken = token.getToken(); JWT jwt; try { jwt = JWTParser.parse(authToken); } catch (ParseException e) { fail("Unable to parse auth token: " + authToken + " exception: ", e); return; } JWTClaimsSet claimsSet; try { claimsSet = jwt.getJWTClaimsSet(); } catch (ParseException e) { fail("Unable to parse claims: " + authToken + " exception: ", e); return; } assertNotNull(claimsSet); assertNotNull(claimsSet.getAudience()); assertFalse(claimsSet.getAudience().isEmpty()); String aud = claimsSet.getAudience().iterator().next(); assertTrue(aud.contains(".webpubsub.azure.com/client/hubs/")); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveNonExistentUserFromGroup() { StepVerifier.create(client.removeUserFromGroupWithResponse("java", "testRemoveNonExistentUserFromGroup", new RequestOptions()), 204); } @Test public void testSendMessageToGroup() { StepVerifier.create(client.sendToGroupWithResponse("java", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain"))), 202); } @Test public void testAadCredential() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .endpoint(TestUtils.getEndpoint()) .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .hub("test"); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())) .connectionString(TestUtils.getConnectionString()); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } final WebPubSubServiceAsyncClient asyncClient = builder.buildAsyncClient(); assertResponse(asyncClient.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testCheckPermission() { assumeTrue(getTestMode() == TestMode.PLAYBACK, "This requires real " + "connection id that is created when a client connects to Web PubSub service. So, run this in PLAYBACK " + "mode only."); RequestOptions requestOptions = new RequestOptions() .addQueryParam("targetName", "java"); StepVerifier.create(client.checkPermissionWithResponse(WebPubSubPermission.SEND_TO_GROUP, "71xtjgThROOJ6DsVY3xbBw2ef45fd11", requestOptions)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); assertTrue(response.getValue()); }) .expectComplete() .verify(TIMEOUT); } }
class WebPubSubServiceAsyncClientTests extends TestProxyTestBase { private static final Duration TIMEOUT = Duration.ofSeconds(10); private static final String USER_ID = "test_user"; private static final RequestOptions REQUEST_OPTIONS_TEXT = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain"); }); private static final RequestOptions REQUEST_OPTIONS_STREAM = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/octet-stream"); }); private static final BinaryData MESSAGE = BinaryData.fromString("Hello World - Broadcast test!"); private WebPubSubServiceAsyncClient client; @Override private static void assertResponse(Mono<Response<Void>> operation) { StepVerifier.create(operation) .assertNext(response -> { assertNotNull(response); assertEquals(202, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testBroadcastString() { assertResponse(client.sendToAllWithResponse(MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testBroadcastStringWithFilter() { RequestOptions requestOptions = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToAllWithResponse(MESSAGE, requestOptions)); } @Test public void testBroadcastBytes() { byte[] bytes = "Hello World - Broadcast test!".getBytes(); assertResponse(client.sendToAllWithResponse(BinaryData.fromBytes(bytes), REQUEST_OPTIONS_STREAM)); } @Test public void testSendToUserString() throws IOException { assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), null)); } } @Test public void testSendToUserStringWithFilter() throws IOException { RequestOptions requestOptions = new RequestOptions() .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), requestOptions)); } } @Test public void testSendToUserBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToUserWithResponse(USER_ID, binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionString() { assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testSendToConnectionStringWithFilter() { final RequestOptions filter = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, filter)); } @Test public void testSendToConnectionBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToConnectionWithResponse("test_connection", binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromString("{\"data\": true}"), requestOptions)); } @Test public void testSendToAllJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"boolvalue\": true}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"stringvalue\": \"testingwebpubsub\"}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"intvalue\": 25}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"floatvalue\": 55.4}"), requestOptions)); } @Test public void testRemoveNonExistentUserFromHub() { StepVerifier.create(client.removeUserFromAllGroupsWithResponse("testRemoveNonExistentUserFromHub", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveConnectionFromAllGroup() { StepVerifier.create(client.removeConnectionFromAllGroupsWithResponse("test_connection", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test @DoNotRecord(skipInPlayback = true) public void testGetAuthenticationToken() { StepVerifier.create(client.getClientAccessToken(new GetClientAccessTokenOptions())) .assertNext(token -> { Assertions.assertNotNull(token); Assertions.assertNotNull(token.getToken()); Assertions.assertNotNull(token.getUrl()); assertTrue(token.getUrl().startsWith("wss: assertTrue(token.getUrl().contains(".webpubsub.azure.com/client/hubs/")); String authToken = token.getToken(); JWT jwt; try { jwt = JWTParser.parse(authToken); } catch (ParseException e) { fail("Unable to parse auth token: " + authToken + " exception: ", e); return; } JWTClaimsSet claimsSet; try { claimsSet = jwt.getJWTClaimsSet(); } catch (ParseException e) { fail("Unable to parse claims: " + authToken + " exception: ", e); return; } assertNotNull(claimsSet); assertNotNull(claimsSet.getAudience()); assertFalse(claimsSet.getAudience().isEmpty()); String aud = claimsSet.getAudience().iterator().next(); assertTrue(aud.contains(".webpubsub.azure.com/client/hubs/")); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveNonExistentUserFromGroup() { StepVerifier.create(client.removeUserFromGroupWithResponse("java", "testRemoveNonExistentUserFromGroup", new RequestOptions()), 204); } @Test public void testSendMessageToGroup() { StepVerifier.create(client.sendToGroupWithResponse("java", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain"))), 202); } @Test public void testAadCredential() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .endpoint(TestUtils.getEndpoint()) .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .hub("test"); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())) .connectionString(TestUtils.getConnectionString()); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } final WebPubSubServiceAsyncClient asyncClient = builder.buildAsyncClient(); assertResponse(asyncClient.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testCheckPermission() { assumeTrue(getTestMode() == TestMode.PLAYBACK, "This requires real " + "connection id that is created when a client connects to Web PubSub service. So, run this in PLAYBACK " + "mode only."); RequestOptions requestOptions = new RequestOptions() .addQueryParam("targetName", "java"); StepVerifier.create(client.checkPermissionWithResponse(WebPubSubPermission.SEND_TO_GROUP, "71xtjgThROOJ6DsVY3xbBw2ef45fd11", requestOptions)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); assertTrue(response.getValue()); }) .expectComplete() .verify(TIMEOUT); } }
It existed to test different overloads in this client I guess.
public void testSendToUserString() throws IOException { assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), null)); } }
try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) {
public void testSendToUserString() throws IOException { assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), null)); } }
class WebPubSubServiceAsyncClientTests extends TestProxyTestBase { private static final Duration TIMEOUT = Duration.ofSeconds(10); private static final String USER_ID = "test_user"; private static final RequestOptions REQUEST_OPTIONS_TEXT = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain"); }); private static final RequestOptions REQUEST_OPTIONS_STREAM = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/octet-stream"); }); private static final BinaryData MESSAGE = BinaryData.fromString("Hello World - Broadcast test!"); private WebPubSubServiceAsyncClient client; @Override protected void beforeTest() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .connectionString(TestUtils.getConnectionString()) .retryOptions(TestUtils.getRetryOptions()) .httpClient(HttpClient.createDefault()) .hub(TestUtils.HUB_NAME); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())); } else if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } this.client = builder.buildAsyncClient(); } private static void assertResponse(Mono<Response<Void>> operation) { StepVerifier.create(operation) .assertNext(response -> { assertNotNull(response); assertEquals(202, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testBroadcastString() { assertResponse(client.sendToAllWithResponse(MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testBroadcastStringWithFilter() { RequestOptions requestOptions = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToAllWithResponse(MESSAGE, requestOptions)); } @Test public void testBroadcastBytes() { byte[] bytes = "Hello World - Broadcast test!".getBytes(); assertResponse(client.sendToAllWithResponse(BinaryData.fromBytes(bytes), REQUEST_OPTIONS_STREAM)); } @Test @Test public void testSendToUserStringWithFilter() throws IOException { RequestOptions requestOptions = new RequestOptions() .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), requestOptions)); } } @Test public void testSendToUserBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToUserWithResponse(USER_ID, binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionString() { assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testSendToConnectionStringWithFilter() { final RequestOptions filter = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, filter)); } @Test public void testSendToConnectionBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToConnectionWithResponse("test_connection", binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromString("{\"data\": true}"), requestOptions)); } @Test public void testSendToAllJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"boolvalue\": true}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"stringvalue\": \"testingwebpubsub\"}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"intvalue\": 25}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"floatvalue\": 55.4}"), requestOptions)); } @Test public void testRemoveNonExistentUserFromHub() { StepVerifier.create(client.removeUserFromAllGroupsWithResponse("testRemoveNonExistentUserFromHub", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveConnectionFromAllGroup() { StepVerifier.create(client.removeConnectionFromAllGroupsWithResponse("test_connection", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test @DoNotRecord(skipInPlayback = true) public void testGetAuthenticationToken() { StepVerifier.create(client.getClientAccessToken(new GetClientAccessTokenOptions())) .assertNext(token -> { Assertions.assertNotNull(token); Assertions.assertNotNull(token.getToken()); Assertions.assertNotNull(token.getUrl()); assertTrue(token.getUrl().startsWith("wss: assertTrue(token.getUrl().contains(".webpubsub.azure.com/client/hubs/")); String authToken = token.getToken(); JWT jwt; try { jwt = JWTParser.parse(authToken); } catch (ParseException e) { fail("Unable to parse auth token: " + authToken + " exception: ", e); return; } JWTClaimsSet claimsSet; try { claimsSet = jwt.getJWTClaimsSet(); } catch (ParseException e) { fail("Unable to parse claims: " + authToken + " exception: ", e); return; } assertNotNull(claimsSet); assertNotNull(claimsSet.getAudience()); assertFalse(claimsSet.getAudience().isEmpty()); String aud = claimsSet.getAudience().iterator().next(); assertTrue(aud.contains(".webpubsub.azure.com/client/hubs/")); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveNonExistentUserFromGroup() { StepVerifier.create(client.removeUserFromGroupWithResponse("java", "testRemoveNonExistentUserFromGroup", new RequestOptions()), 204); } @Test public void testSendMessageToGroup() { StepVerifier.create(client.sendToGroupWithResponse("java", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain"))), 202); } @Test public void testAadCredential() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .endpoint(TestUtils.getEndpoint()) .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .hub("test"); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())) .connectionString(TestUtils.getConnectionString()); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } final WebPubSubServiceAsyncClient asyncClient = builder.buildAsyncClient(); assertResponse(asyncClient.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testCheckPermission() { assumeTrue(getTestMode() == TestMode.PLAYBACK, "This requires real " + "connection id that is created when a client connects to Web PubSub service. So, run this in PLAYBACK " + "mode only."); RequestOptions requestOptions = new RequestOptions() .addQueryParam("targetName", "java"); StepVerifier.create(client.checkPermissionWithResponse(WebPubSubPermission.SEND_TO_GROUP, "71xtjgThROOJ6DsVY3xbBw2ef45fd11", requestOptions)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); assertTrue(response.getValue()); }) .expectComplete() .verify(TIMEOUT); } }
class WebPubSubServiceAsyncClientTests extends TestProxyTestBase { private static final Duration TIMEOUT = Duration.ofSeconds(10); private static final String USER_ID = "test_user"; private static final RequestOptions REQUEST_OPTIONS_TEXT = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain"); }); private static final RequestOptions REQUEST_OPTIONS_STREAM = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/octet-stream"); }); private static final BinaryData MESSAGE = BinaryData.fromString("Hello World - Broadcast test!"); private WebPubSubServiceAsyncClient client; @Override protected void beforeTest() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .connectionString(TestUtils.getConnectionString()) .retryOptions(TestUtils.getRetryOptions()) .hub(TestUtils.HUB_NAME); switch (getTestMode()) { case LIVE: builder.httpClient(HttpClient.createDefault()); break; case RECORD: builder.httpClient(HttpClient.createDefault()) .addPolicy(interceptorManager.getRecordPolicy()); break; case PLAYBACK: builder.httpClient(interceptorManager.getPlaybackClient()); break; default: throw new IllegalStateException("Unknown test mode. " + getTestMode()); } this.client = builder.buildAsyncClient(); } private static void assertResponse(Mono<Response<Void>> operation) { StepVerifier.create(operation) .assertNext(response -> { assertNotNull(response); assertEquals(202, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testBroadcastString() { assertResponse(client.sendToAllWithResponse(MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testBroadcastStringWithFilter() { RequestOptions requestOptions = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToAllWithResponse(MESSAGE, requestOptions)); } @Test public void testBroadcastBytes() { byte[] bytes = "Hello World - Broadcast test!".getBytes(); assertResponse(client.sendToAllWithResponse(BinaryData.fromBytes(bytes), REQUEST_OPTIONS_STREAM)); } @Test @Test public void testSendToUserStringWithFilter() throws IOException { RequestOptions requestOptions = new RequestOptions() .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), requestOptions)); } } @Test public void testSendToUserBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToUserWithResponse(USER_ID, binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionString() { assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testSendToConnectionStringWithFilter() { final RequestOptions filter = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, filter)); } @Test public void testSendToConnectionBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToConnectionWithResponse("test_connection", binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromString("{\"data\": true}"), requestOptions)); } @Test public void testSendToAllJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"boolvalue\": true}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"stringvalue\": \"testingwebpubsub\"}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"intvalue\": 25}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"floatvalue\": 55.4}"), requestOptions)); } @Test public void testRemoveNonExistentUserFromHub() { StepVerifier.create(client.removeUserFromAllGroupsWithResponse("testRemoveNonExistentUserFromHub", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveConnectionFromAllGroup() { StepVerifier.create(client.removeConnectionFromAllGroupsWithResponse("test_connection", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test @DoNotRecord(skipInPlayback = true) public void testGetAuthenticationToken() { StepVerifier.create(client.getClientAccessToken(new GetClientAccessTokenOptions())) .assertNext(token -> { Assertions.assertNotNull(token); Assertions.assertNotNull(token.getToken()); Assertions.assertNotNull(token.getUrl()); assertTrue(token.getUrl().startsWith("wss: assertTrue(token.getUrl().contains(".webpubsub.azure.com/client/hubs/")); String authToken = token.getToken(); JWT jwt; try { jwt = JWTParser.parse(authToken); } catch (ParseException e) { fail("Unable to parse auth token: " + authToken + " exception: ", e); return; } JWTClaimsSet claimsSet; try { claimsSet = jwt.getJWTClaimsSet(); } catch (ParseException e) { fail("Unable to parse claims: " + authToken + " exception: ", e); return; } assertNotNull(claimsSet); assertNotNull(claimsSet.getAudience()); assertFalse(claimsSet.getAudience().isEmpty()); String aud = claimsSet.getAudience().iterator().next(); assertTrue(aud.contains(".webpubsub.azure.com/client/hubs/")); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveNonExistentUserFromGroup() { StepVerifier.create(client.removeUserFromGroupWithResponse("java", "testRemoveNonExistentUserFromGroup", new RequestOptions()), 204); } @Test public void testSendMessageToGroup() { StepVerifier.create(client.sendToGroupWithResponse("java", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain"))), 202); } @Test public void testAadCredential() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .endpoint(TestUtils.getEndpoint()) .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .hub("test"); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())) .connectionString(TestUtils.getConnectionString()); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } final WebPubSubServiceAsyncClient asyncClient = builder.buildAsyncClient(); assertResponse(asyncClient.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testCheckPermission() { assumeTrue(getTestMode() == TestMode.PLAYBACK, "This requires real " + "connection id that is created when a client connects to Web PubSub service. So, run this in PLAYBACK " + "mode only."); RequestOptions requestOptions = new RequestOptions() .addQueryParam("targetName", "java"); StepVerifier.create(client.checkPermissionWithResponse(WebPubSubPermission.SEND_TO_GROUP, "71xtjgThROOJ6DsVY3xbBw2ef45fd11", requestOptions)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); assertTrue(response.getValue()); }) .expectComplete() .verify(TIMEOUT); } }
It made the recordings frustrating to read. I can enable them all for LIVE tests.
protected void beforeTest() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .connectionString(TestUtils.getConnectionString()) .retryOptions(TestUtils.getRetryOptions()) .httpClient(HttpClient.createDefault()) .hub(TestUtils.HUB_NAME); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())); } else if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } this.client = builder.buildAsyncClient(); }
.retryOptions(TestUtils.getRetryOptions())
protected void beforeTest() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .connectionString(TestUtils.getConnectionString()) .retryOptions(TestUtils.getRetryOptions()) .hub(TestUtils.HUB_NAME); switch (getTestMode()) { case LIVE: builder.httpClient(HttpClient.createDefault()); break; case RECORD: builder.httpClient(HttpClient.createDefault()) .addPolicy(interceptorManager.getRecordPolicy()); break; case PLAYBACK: builder.httpClient(interceptorManager.getPlaybackClient()); break; default: throw new IllegalStateException("Unknown test mode. " + getTestMode()); } this.client = builder.buildAsyncClient(); }
class WebPubSubServiceAsyncClientTests extends TestProxyTestBase { private static final Duration TIMEOUT = Duration.ofSeconds(10); private static final String USER_ID = "test_user"; private static final RequestOptions REQUEST_OPTIONS_TEXT = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain"); }); private static final RequestOptions REQUEST_OPTIONS_STREAM = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/octet-stream"); }); private static final BinaryData MESSAGE = BinaryData.fromString("Hello World - Broadcast test!"); private WebPubSubServiceAsyncClient client; @Override private static void assertResponse(Mono<Response<Void>> operation) { StepVerifier.create(operation) .assertNext(response -> { assertNotNull(response); assertEquals(202, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testBroadcastString() { assertResponse(client.sendToAllWithResponse(MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testBroadcastStringWithFilter() { RequestOptions requestOptions = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToAllWithResponse(MESSAGE, requestOptions)); } @Test public void testBroadcastBytes() { byte[] bytes = "Hello World - Broadcast test!".getBytes(); assertResponse(client.sendToAllWithResponse(BinaryData.fromBytes(bytes), REQUEST_OPTIONS_STREAM)); } @Test public void testSendToUserString() throws IOException { assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), null)); } } @Test public void testSendToUserStringWithFilter() throws IOException { RequestOptions requestOptions = new RequestOptions() .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), requestOptions)); } } @Test public void testSendToUserBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToUserWithResponse(USER_ID, binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionString() { assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testSendToConnectionStringWithFilter() { final RequestOptions filter = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, filter)); } @Test public void testSendToConnectionBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToConnectionWithResponse("test_connection", binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromString("{\"data\": true}"), requestOptions)); } @Test public void testSendToAllJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"boolvalue\": true}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"stringvalue\": \"testingwebpubsub\"}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"intvalue\": 25}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"floatvalue\": 55.4}"), requestOptions)); } @Test public void testRemoveNonExistentUserFromHub() { StepVerifier.create(client.removeUserFromAllGroupsWithResponse("testRemoveNonExistentUserFromHub", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveConnectionFromAllGroup() { StepVerifier.create(client.removeConnectionFromAllGroupsWithResponse("test_connection", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test @DoNotRecord(skipInPlayback = true) public void testGetAuthenticationToken() { StepVerifier.create(client.getClientAccessToken(new GetClientAccessTokenOptions())) .assertNext(token -> { Assertions.assertNotNull(token); Assertions.assertNotNull(token.getToken()); Assertions.assertNotNull(token.getUrl()); assertTrue(token.getUrl().startsWith("wss: assertTrue(token.getUrl().contains(".webpubsub.azure.com/client/hubs/")); String authToken = token.getToken(); JWT jwt; try { jwt = JWTParser.parse(authToken); } catch (ParseException e) { fail("Unable to parse auth token: " + authToken + " exception: ", e); return; } JWTClaimsSet claimsSet; try { claimsSet = jwt.getJWTClaimsSet(); } catch (ParseException e) { fail("Unable to parse claims: " + authToken + " exception: ", e); return; } assertNotNull(claimsSet); assertNotNull(claimsSet.getAudience()); assertFalse(claimsSet.getAudience().isEmpty()); String aud = claimsSet.getAudience().iterator().next(); assertTrue(aud.contains(".webpubsub.azure.com/client/hubs/")); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveNonExistentUserFromGroup() { StepVerifier.create(client.removeUserFromGroupWithResponse("java", "testRemoveNonExistentUserFromGroup", new RequestOptions()), 204); } @Test public void testSendMessageToGroup() { StepVerifier.create(client.sendToGroupWithResponse("java", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain"))), 202); } @Test public void testAadCredential() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .endpoint(TestUtils.getEndpoint()) .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .hub("test"); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())) .connectionString(TestUtils.getConnectionString()); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } final WebPubSubServiceAsyncClient asyncClient = builder.buildAsyncClient(); assertResponse(asyncClient.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testCheckPermission() { assumeTrue(getTestMode() == TestMode.PLAYBACK, "This requires real " + "connection id that is created when a client connects to Web PubSub service. So, run this in PLAYBACK " + "mode only."); RequestOptions requestOptions = new RequestOptions() .addQueryParam("targetName", "java"); StepVerifier.create(client.checkPermissionWithResponse(WebPubSubPermission.SEND_TO_GROUP, "71xtjgThROOJ6DsVY3xbBw2ef45fd11", requestOptions)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); assertTrue(response.getValue()); }) .expectComplete() .verify(TIMEOUT); } }
class WebPubSubServiceAsyncClientTests extends TestProxyTestBase { private static final Duration TIMEOUT = Duration.ofSeconds(10); private static final String USER_ID = "test_user"; private static final RequestOptions REQUEST_OPTIONS_TEXT = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain"); }); private static final RequestOptions REQUEST_OPTIONS_STREAM = new RequestOptions() .addRequestCallback(request -> { request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/octet-stream"); }); private static final BinaryData MESSAGE = BinaryData.fromString("Hello World - Broadcast test!"); private WebPubSubServiceAsyncClient client; @Override private static void assertResponse(Mono<Response<Void>> operation) { StepVerifier.create(operation) .assertNext(response -> { assertNotNull(response); assertEquals(202, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testBroadcastString() { assertResponse(client.sendToAllWithResponse(MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testBroadcastStringWithFilter() { RequestOptions requestOptions = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToAllWithResponse(MESSAGE, requestOptions)); } @Test public void testBroadcastBytes() { byte[] bytes = "Hello World - Broadcast test!".getBytes(); assertResponse(client.sendToAllWithResponse(BinaryData.fromBytes(bytes), REQUEST_OPTIONS_STREAM)); } @Test public void testSendToUserString() throws IOException { assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), null)); } } @Test public void testSendToUserStringWithFilter() throws IOException { RequestOptions requestOptions = new RequestOptions() .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); assertResponse(client.sendToUserWithResponse(USER_ID, MESSAGE, WebPubSubContentType.TEXT_PLAIN, MESSAGE.getLength(), null)); try (ByteArrayInputStream messageStream = new ByteArrayInputStream(MESSAGE.toBytes())) { assertResponse(client.sendToUserWithResponse(USER_ID, BinaryData.fromStream(messageStream), WebPubSubContentType.APPLICATION_OCTET_STREAM, MESSAGE.getLength(), requestOptions)); } } @Test public void testSendToUserBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToUserWithResponse(USER_ID, binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionString() { assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testSendToConnectionStringWithFilter() { final RequestOptions filter = new RequestOptions() .setHeader(HttpHeaderName.CONTENT_TYPE, "text/plain") .addQueryParam("filter", "userId ne 'user1'"); assertResponse(client.sendToConnectionWithResponse("test_connection", MESSAGE, filter)); } @Test public void testSendToConnectionBytes() { final BinaryData binaryData = BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)); assertResponse(client.sendToConnectionWithResponse("test_connection", binaryData, REQUEST_OPTIONS_STREAM)); } @Test public void testSendToConnectionJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromString("{\"data\": true}"), requestOptions)); } @Test public void testSendToAllJson() { RequestOptions requestOptions = new RequestOptions() .addRequestCallback(request -> request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"boolvalue\": true}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"stringvalue\": \"testingwebpubsub\"}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"intvalue\": 25}"), requestOptions)); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"floatvalue\": 55.4}"), requestOptions)); } @Test public void testRemoveNonExistentUserFromHub() { StepVerifier.create(client.removeUserFromAllGroupsWithResponse("testRemoveNonExistentUserFromHub", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveConnectionFromAllGroup() { StepVerifier.create(client.removeConnectionFromAllGroupsWithResponse("test_connection", new RequestOptions())) .assertNext(response -> { assertEquals(204, response.getStatusCode()); }) .expectComplete() .verify(TIMEOUT); } @Test @DoNotRecord(skipInPlayback = true) public void testGetAuthenticationToken() { StepVerifier.create(client.getClientAccessToken(new GetClientAccessTokenOptions())) .assertNext(token -> { Assertions.assertNotNull(token); Assertions.assertNotNull(token.getToken()); Assertions.assertNotNull(token.getUrl()); assertTrue(token.getUrl().startsWith("wss: assertTrue(token.getUrl().contains(".webpubsub.azure.com/client/hubs/")); String authToken = token.getToken(); JWT jwt; try { jwt = JWTParser.parse(authToken); } catch (ParseException e) { fail("Unable to parse auth token: " + authToken + " exception: ", e); return; } JWTClaimsSet claimsSet; try { claimsSet = jwt.getJWTClaimsSet(); } catch (ParseException e) { fail("Unable to parse claims: " + authToken + " exception: ", e); return; } assertNotNull(claimsSet); assertNotNull(claimsSet.getAudience()); assertFalse(claimsSet.getAudience().isEmpty()); String aud = claimsSet.getAudience().iterator().next(); assertTrue(aud.contains(".webpubsub.azure.com/client/hubs/")); }) .expectComplete() .verify(TIMEOUT); } @Test public void testRemoveNonExistentUserFromGroup() { StepVerifier.create(client.removeUserFromGroupWithResponse("java", "testRemoveNonExistentUserFromGroup", new RequestOptions()), 204); } @Test public void testSendMessageToGroup() { StepVerifier.create(client.sendToGroupWithResponse("java", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain"))), 202); } @Test public void testAadCredential() { WebPubSubServiceClientBuilder builder = new WebPubSubServiceClientBuilder() .endpoint(TestUtils.getEndpoint()) .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .hub("test"); if (getTestMode() == TestMode.PLAYBACK) { builder.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient())) .connectionString(TestUtils.getConnectionString()); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } if (getTestMode() == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()); } final WebPubSubServiceAsyncClient asyncClient = builder.buildAsyncClient(); assertResponse(asyncClient.sendToUserWithResponse(USER_ID, MESSAGE, REQUEST_OPTIONS_TEXT)); } @Test public void testCheckPermission() { assumeTrue(getTestMode() == TestMode.PLAYBACK, "This requires real " + "connection id that is created when a client connects to Web PubSub service. So, run this in PLAYBACK " + "mode only."); RequestOptions requestOptions = new RequestOptions() .addQueryParam("targetName", "java"); StepVerifier.create(client.checkPermissionWithResponse(WebPubSubPermission.SEND_TO_GROUP, "71xtjgThROOJ6DsVY3xbBw2ef45fd11", requestOptions)) .assertNext(response -> { assertEquals(200, response.getStatusCode()); assertTrue(response.getValue()); }) .expectComplete() .verify(TIMEOUT); } }
I don't see any sanitizer added, so then why the BodilessMatcher?
QuantumClientBuilder getClientBuilder(HttpClient httpClient) { QuantumClientBuilder builder = new QuantumClientBuilder(); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); builder.httpClient(interceptorManager.getPlaybackClient()); } else { builder.httpClient(httpClient) .credential(new AzureCliCredentialBuilder().build()); } return builder.subscriptionId(getSubscriptionId()) .resourceGroupName(getResourceGroup()) .workspaceName(getWorkspaceName()) .host(getEndpoint()); }
customMatchers.add(new BodilessMatcher());
QuantumClientBuilder getClientBuilder(HttpClient httpClient) { QuantumClientBuilder builder = new QuantumClientBuilder(); if (interceptorManager.isRecordMode() || interceptorManager.isPlaybackMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..containerUri", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..inputDataUri", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..outputDataUri", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); builder.httpClient(interceptorManager.getPlaybackClient()); } else { builder.httpClient(httpClient) .credential(new AzureCliCredentialBuilder().build()); } return builder.subscriptionId(getSubscriptionId()) .resourceGroupName(getResourceGroup()) .workspaceName(getWorkspaceName()) .host(getEndpoint()); }
class QuantumClientTestBase extends TestProxyTestBase { private final String endpoint = Configuration.getGlobalConfiguration().get("QUANTUM_ENDPOINT"); private final String subscriptionId = Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); private final String resourceGroup = Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_RESOURCE_GROUP); private final String workspaceName = Configuration.getGlobalConfiguration().get("QUANTUM_WORKSPACE"); String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : endpoint; } String getSubscriptionId() { return testResourceNamer.recordValueFromConfig(subscriptionId); } String getResourceGroup() { return testResourceNamer.recordValueFromConfig(resourceGroup); } String getWorkspaceName() { return testResourceNamer.recordValueFromConfig(workspaceName); } }
class QuantumClientTestBase extends TestProxyTestBase { private final String endpoint = Configuration.getGlobalConfiguration().get("QUANTUM_ENDPOINT"); private final String subscriptionId = Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); private final String resourceGroup = Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_RESOURCE_GROUP); private final String workspaceName = Configuration.getGlobalConfiguration().get("QUANTUM_WORKSPACE"); String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : endpoint; } String getSubscriptionId() { return testResourceNamer.recordValueFromConfig(subscriptionId); } String getResourceGroup() { return testResourceNamer.recordValueFromConfig(resourceGroup); } String getWorkspaceName() { return testResourceNamer.recordValueFromConfig(workspaceName); } }
this should be a btter api for matcher header key only https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-test/src/main/java/com/azure/core/test/models/CustomMatcher.java#L69
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( GeolocationClientBuilder.GEOLOCATION_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("subscription-key")));
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( GeolocationClientBuilder.GEOLOCATION_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
class GeolocationClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } GeolocationClientBuilder getGeoLocationAsyncClientBuilder(HttpClient httpClient, GeolocationServiceVersion serviceVersion) { GeolocationClientBuilder builder = new GeolocationClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetLocation(IpAddressToLocationResult expected, IpAddressToLocationResult actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCountryRegion().getIsoCode(), actual.getCountryRegion().getIsoCode()); assertEquals(expected.getIpAddress(), actual.getIpAddress()); } static void validateGetLocationWithResponse(IpAddressToLocationResult expected, int expectedStatusCode, Response<IpAddressToLocationResult> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetLocation(expected, response.getValue()); } }
class GeolocationClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } GeolocationClientBuilder getGeoLocationAsyncClientBuilder(HttpClient httpClient, GeolocationServiceVersion serviceVersion) { GeolocationClientBuilder builder = new GeolocationClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetLocation(IpAddressToLocationResult expected, IpAddressToLocationResult actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCountryRegion().getIsoCode(), actual.getCountryRegion().getIsoCode()); assertEquals(expected.getIpAddress(), actual.getIpAddress()); } static void validateGetLocationWithResponse(IpAddressToLocationResult expected, int expectedStatusCode, Response<IpAddressToLocationResult> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetLocation(expected, response.getValue()); } }
Shouldn't this be done in the builder?
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( GeolocationClientBuilder.GEOLOCATION_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16))));
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( GeolocationClientBuilder.GEOLOCATION_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
class GeolocationClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } GeolocationClientBuilder getGeoLocationAsyncClientBuilder(HttpClient httpClient, GeolocationServiceVersion serviceVersion) { GeolocationClientBuilder builder = new GeolocationClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetLocation(IpAddressToLocationResult expected, IpAddressToLocationResult actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCountryRegion().getIsoCode(), actual.getCountryRegion().getIsoCode()); assertEquals(expected.getIpAddress(), actual.getIpAddress()); } static void validateGetLocationWithResponse(IpAddressToLocationResult expected, int expectedStatusCode, Response<IpAddressToLocationResult> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetLocation(expected, response.getValue()); } }
class GeolocationClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } GeolocationClientBuilder getGeoLocationAsyncClientBuilder(HttpClient httpClient, GeolocationServiceVersion serviceVersion) { GeolocationClientBuilder builder = new GeolocationClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetLocation(IpAddressToLocationResult expected, IpAddressToLocationResult actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCountryRegion().getIsoCode(), actual.getCountryRegion().getIsoCode()); assertEquals(expected.getIpAddress(), actual.getIpAddress()); } static void validateGetLocationWithResponse(IpAddressToLocationResult expected, int expectedStatusCode, Response<IpAddressToLocationResult> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetLocation(expected, response.getValue()); } }
We can do that, I just followed a pattern we also have on Key Vault. I'll try to use the builder instead.
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( GeolocationClientBuilder.GEOLOCATION_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16))));
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( GeolocationClientBuilder.GEOLOCATION_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
class GeolocationClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } GeolocationClientBuilder getGeoLocationAsyncClientBuilder(HttpClient httpClient, GeolocationServiceVersion serviceVersion) { GeolocationClientBuilder builder = new GeolocationClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetLocation(IpAddressToLocationResult expected, IpAddressToLocationResult actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCountryRegion().getIsoCode(), actual.getCountryRegion().getIsoCode()); assertEquals(expected.getIpAddress(), actual.getIpAddress()); } static void validateGetLocationWithResponse(IpAddressToLocationResult expected, int expectedStatusCode, Response<IpAddressToLocationResult> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetLocation(expected, response.getValue()); } }
class GeolocationClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } GeolocationClientBuilder getGeoLocationAsyncClientBuilder(HttpClient httpClient, GeolocationServiceVersion serviceVersion) { GeolocationClientBuilder builder = new GeolocationClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetLocation(IpAddressToLocationResult expected, IpAddressToLocationResult actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCountryRegion().getIsoCode(), actual.getCountryRegion().getIsoCode()); assertEquals(expected.getIpAddress(), actual.getIpAddress()); } static void validateGetLocationWithResponse(IpAddressToLocationResult expected, int expectedStatusCode, Response<IpAddressToLocationResult> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetLocation(expected, response.getValue()); } }
Cool, thanks!
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( GeolocationClientBuilder.GEOLOCATION_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("subscription-key")));
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( GeolocationClientBuilder.GEOLOCATION_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
class GeolocationClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } GeolocationClientBuilder getGeoLocationAsyncClientBuilder(HttpClient httpClient, GeolocationServiceVersion serviceVersion) { GeolocationClientBuilder builder = new GeolocationClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetLocation(IpAddressToLocationResult expected, IpAddressToLocationResult actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCountryRegion().getIsoCode(), actual.getCountryRegion().getIsoCode()); assertEquals(expected.getIpAddress(), actual.getIpAddress()); } static void validateGetLocationWithResponse(IpAddressToLocationResult expected, int expectedStatusCode, Response<IpAddressToLocationResult> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetLocation(expected, response.getValue()); } }
class GeolocationClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } GeolocationClientBuilder getGeoLocationAsyncClientBuilder(HttpClient httpClient, GeolocationServiceVersion serviceVersion) { GeolocationClientBuilder builder = new GeolocationClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetLocation(IpAddressToLocationResult expected, IpAddressToLocationResult actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCountryRegion().getIsoCode(), actual.getCountryRegion().getIsoCode()); assertEquals(expected.getIpAddress(), actual.getIpAddress()); } static void validateGetLocationWithResponse(IpAddressToLocationResult expected, int expectedStatusCode, Response<IpAddressToLocationResult> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetLocation(expected, response.getValue()); } }
I decided to keep things as-is, it's easier to use `HttpPolicyProviders.addBeforeRetryPolicies()` and `HttpPolicyProviders.addAfterRetryPolicies()`, as well as `HttpPipelineBuilder.policies()` method to add all the policies that will come into effect. Else, I would have to do that one by one with `GeolocationClientBuilder.addPolicy()`.
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( GeolocationClientBuilder.GEOLOCATION_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16))));
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( GeolocationClientBuilder.GEOLOCATION_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
class GeolocationClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } GeolocationClientBuilder getGeoLocationAsyncClientBuilder(HttpClient httpClient, GeolocationServiceVersion serviceVersion) { GeolocationClientBuilder builder = new GeolocationClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetLocation(IpAddressToLocationResult expected, IpAddressToLocationResult actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCountryRegion().getIsoCode(), actual.getCountryRegion().getIsoCode()); assertEquals(expected.getIpAddress(), actual.getIpAddress()); } static void validateGetLocationWithResponse(IpAddressToLocationResult expected, int expectedStatusCode, Response<IpAddressToLocationResult> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetLocation(expected, response.getValue()); } }
class GeolocationClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } GeolocationClientBuilder getGeoLocationAsyncClientBuilder(HttpClient httpClient, GeolocationServiceVersion serviceVersion) { GeolocationClientBuilder builder = new GeolocationClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetLocation(IpAddressToLocationResult expected, IpAddressToLocationResult actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCountryRegion().getIsoCode(), actual.getCountryRegion().getIsoCode()); assertEquals(expected.getIpAddress(), actual.getIpAddress()); } static void validateGetLocationWithResponse(IpAddressToLocationResult expected, int expectedStatusCode, Response<IpAddressToLocationResult> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetLocation(expected, response.getValue()); } }
why the check for 0? to only write it once when it is initially 0?
public void setIndex(int index) { if (this.index == 0) { this.index = index; } }
if (this.index == 0) {
public void setIndex(int index) { if (this.index == 0) { this.index = index; } }
class ItemBulkOperation<TInternal, TContext> extends CosmosItemOperationBase implements Comparable<CosmosItemOperation> { private final TInternal item; private final TContext context; private final String id; private final PartitionKey partitionKey; private final CosmosItemOperationType operationType; private final RequestOptions requestOptions; private String partitionKeyJson; private BulkOperationRetryPolicy bulkOperationRetryPolicy; /** index for preserve ordering in Bulk Executor */ private int index; public ItemBulkOperation( CosmosItemOperationType operationType, String id, PartitionKey partitionKey, RequestOptions requestOptions, TInternal item, TContext context) { checkNotNull(operationType, "expected non-null operationType"); this.operationType = operationType; this.partitionKey = partitionKey; this.id = id; this.item = item; this.context = context; this.requestOptions = requestOptions; } /** * Writes a single operation to JsonSerializable. * TODO(rakkuma): Similarly for hybrid row, operation needs to be written in Hybrid row. * Issue: https: * * @return instance of JsonSerializable containing values for a operation. */ @Override JsonSerializable getSerializedOperationInternal() { final JsonSerializable jsonSerializable = new JsonSerializable(); jsonSerializable.set( BatchRequestResponseConstants.FIELD_OPERATION_TYPE, ModelBridgeInternal.getOperationValueForCosmosItemOperationType(this.getOperationType())); if (StringUtils.isNotEmpty(this.getPartitionKeyJson())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_PARTITION_KEY, this.getPartitionKeyJson()); } if (StringUtils.isNotEmpty(this.getId())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_ID, this.getId()); } if (this.getItemInternal() != null) { if (this.getOperationType() == CosmosItemOperationType.PATCH) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_RESOURCE_BODY, PatchUtil.serializableBatchPatchOperation((CosmosPatchOperations) this.getItemInternal(), this.getRequestOptions())); } else { jsonSerializable.set(BatchRequestResponseConstants.FIELD_RESOURCE_BODY, this.getItemInternal()); } } if (this.getRequestOptions() != null) { RequestOptions requestOptions = this.getRequestOptions(); if (StringUtils.isNotEmpty(requestOptions.getIfMatchETag())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_IF_MATCH, requestOptions.getIfMatchETag()); } if (StringUtils.isNotEmpty(requestOptions.getIfNoneMatchETag())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_IF_NONE_MATCH, requestOptions.getIfNoneMatchETag()); } if (requestOptions.isContentResponseOnWriteEnabled() != null) { if (!requestOptions.isContentResponseOnWriteEnabled() && BulkExecutorUtil.isWriteOperation(operationType)) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_MINIMAL_RETURN_PREFERENCE, true); } } } return jsonSerializable; } public int getIndex() { return index; } TInternal getItemInternal() { return this.item; } @SuppressWarnings("unchecked") public <T> T getItem() { return (T)this.item; } @SuppressWarnings("unchecked") public <T> T getContext() { return (T)this.context; } public String getId() { return this.id; } public PartitionKey getPartitionKeyValue() { return partitionKey; } public CosmosItemOperationType getOperationType() { return this.operationType; } public RequestOptions getRequestOptions() { return this.requestOptions; } private String getPartitionKeyJson() { return partitionKeyJson; } void setPartitionKeyJson(String value) { partitionKeyJson = value; } BulkOperationRetryPolicy getRetryPolicy() { return bulkOperationRetryPolicy; } void setRetryPolicy(BulkOperationRetryPolicy bulkOperationRetryPolicy) { this.bulkOperationRetryPolicy = bulkOperationRetryPolicy; } @Override public int compareTo(CosmosItemOperation operation) { if (operation instanceof ItemBulkOperation) { ItemBulkOperation<?, ?> bulkOperation = (ItemBulkOperation<?, ?>) operation; return this.index - bulkOperation.index; } return 0; } @Override public boolean equals(Object obj) { return super.equals(obj); } @Override public int hashCode() { return super.hashCode(); } }
class ItemBulkOperation<TInternal, TContext> extends CosmosItemOperationBase implements Comparable<CosmosItemOperation> { private final TInternal item; private final TContext context; private final String id; private final PartitionKey partitionKey; private final CosmosItemOperationType operationType; private final RequestOptions requestOptions; private String partitionKeyJson; private BulkOperationRetryPolicy bulkOperationRetryPolicy; /** index for preserve ordering in Bulk Executor */ private int index; public ItemBulkOperation( CosmosItemOperationType operationType, String id, PartitionKey partitionKey, RequestOptions requestOptions, TInternal item, TContext context) { checkNotNull(operationType, "expected non-null operationType"); this.operationType = operationType; this.partitionKey = partitionKey; this.id = id; this.item = item; this.context = context; this.requestOptions = requestOptions; this.index = 0; } /** * Writes a single operation to JsonSerializable. * TODO(rakkuma): Similarly for hybrid row, operation needs to be written in Hybrid row. * Issue: https: * * @return instance of JsonSerializable containing values for a operation. */ @Override JsonSerializable getSerializedOperationInternal() { final JsonSerializable jsonSerializable = new JsonSerializable(); jsonSerializable.set( BatchRequestResponseConstants.FIELD_OPERATION_TYPE, ModelBridgeInternal.getOperationValueForCosmosItemOperationType(this.getOperationType())); if (StringUtils.isNotEmpty(this.getPartitionKeyJson())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_PARTITION_KEY, this.getPartitionKeyJson()); } if (StringUtils.isNotEmpty(this.getId())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_ID, this.getId()); } if (this.getItemInternal() != null) { if (this.getOperationType() == CosmosItemOperationType.PATCH) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_RESOURCE_BODY, PatchUtil.serializableBatchPatchOperation((CosmosPatchOperations) this.getItemInternal(), this.getRequestOptions())); } else { jsonSerializable.set(BatchRequestResponseConstants.FIELD_RESOURCE_BODY, this.getItemInternal()); } } if (this.getRequestOptions() != null) { RequestOptions requestOptions = this.getRequestOptions(); if (StringUtils.isNotEmpty(requestOptions.getIfMatchETag())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_IF_MATCH, requestOptions.getIfMatchETag()); } if (StringUtils.isNotEmpty(requestOptions.getIfNoneMatchETag())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_IF_NONE_MATCH, requestOptions.getIfNoneMatchETag()); } if (requestOptions.isContentResponseOnWriteEnabled() != null) { if (!requestOptions.isContentResponseOnWriteEnabled() && BulkExecutorUtil.isWriteOperation(operationType)) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_MINIMAL_RETURN_PREFERENCE, true); } } } return jsonSerializable; } public int getIndex() { return index; } TInternal getItemInternal() { return this.item; } @SuppressWarnings("unchecked") public <T> T getItem() { return (T)this.item; } @SuppressWarnings("unchecked") public <T> T getContext() { return (T)this.context; } public String getId() { return this.id; } public PartitionKey getPartitionKeyValue() { return partitionKey; } public CosmosItemOperationType getOperationType() { return this.operationType; } public RequestOptions getRequestOptions() { return this.requestOptions; } private String getPartitionKeyJson() { return partitionKeyJson; } void setPartitionKeyJson(String value) { partitionKeyJson = value; } BulkOperationRetryPolicy getRetryPolicy() { return bulkOperationRetryPolicy; } void setRetryPolicy(BulkOperationRetryPolicy bulkOperationRetryPolicy) { this.bulkOperationRetryPolicy = bulkOperationRetryPolicy; } @Override public int compareTo(CosmosItemOperation operation) { if (operation instanceof ItemBulkOperation) { ItemBulkOperation<?, ?> bulkOperation = (ItemBulkOperation<?, ?>) operation; return this.index - bulkOperation.index; } return 0; } @Override public boolean equals(Object obj) { return super.equals(obj); } @Override public int hashCode() { return super.hashCode(); } }
Yes to only set it once. If not, it is possible that the index will be changed when the operation fails due to a partition split.
public void setIndex(int index) { if (this.index == 0) { this.index = index; } }
if (this.index == 0) {
public void setIndex(int index) { if (this.index == 0) { this.index = index; } }
class ItemBulkOperation<TInternal, TContext> extends CosmosItemOperationBase implements Comparable<CosmosItemOperation> { private final TInternal item; private final TContext context; private final String id; private final PartitionKey partitionKey; private final CosmosItemOperationType operationType; private final RequestOptions requestOptions; private String partitionKeyJson; private BulkOperationRetryPolicy bulkOperationRetryPolicy; /** index for preserve ordering in Bulk Executor */ private int index; public ItemBulkOperation( CosmosItemOperationType operationType, String id, PartitionKey partitionKey, RequestOptions requestOptions, TInternal item, TContext context) { checkNotNull(operationType, "expected non-null operationType"); this.operationType = operationType; this.partitionKey = partitionKey; this.id = id; this.item = item; this.context = context; this.requestOptions = requestOptions; } /** * Writes a single operation to JsonSerializable. * TODO(rakkuma): Similarly for hybrid row, operation needs to be written in Hybrid row. * Issue: https: * * @return instance of JsonSerializable containing values for a operation. */ @Override JsonSerializable getSerializedOperationInternal() { final JsonSerializable jsonSerializable = new JsonSerializable(); jsonSerializable.set( BatchRequestResponseConstants.FIELD_OPERATION_TYPE, ModelBridgeInternal.getOperationValueForCosmosItemOperationType(this.getOperationType())); if (StringUtils.isNotEmpty(this.getPartitionKeyJson())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_PARTITION_KEY, this.getPartitionKeyJson()); } if (StringUtils.isNotEmpty(this.getId())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_ID, this.getId()); } if (this.getItemInternal() != null) { if (this.getOperationType() == CosmosItemOperationType.PATCH) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_RESOURCE_BODY, PatchUtil.serializableBatchPatchOperation((CosmosPatchOperations) this.getItemInternal(), this.getRequestOptions())); } else { jsonSerializable.set(BatchRequestResponseConstants.FIELD_RESOURCE_BODY, this.getItemInternal()); } } if (this.getRequestOptions() != null) { RequestOptions requestOptions = this.getRequestOptions(); if (StringUtils.isNotEmpty(requestOptions.getIfMatchETag())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_IF_MATCH, requestOptions.getIfMatchETag()); } if (StringUtils.isNotEmpty(requestOptions.getIfNoneMatchETag())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_IF_NONE_MATCH, requestOptions.getIfNoneMatchETag()); } if (requestOptions.isContentResponseOnWriteEnabled() != null) { if (!requestOptions.isContentResponseOnWriteEnabled() && BulkExecutorUtil.isWriteOperation(operationType)) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_MINIMAL_RETURN_PREFERENCE, true); } } } return jsonSerializable; } public int getIndex() { return index; } TInternal getItemInternal() { return this.item; } @SuppressWarnings("unchecked") public <T> T getItem() { return (T)this.item; } @SuppressWarnings("unchecked") public <T> T getContext() { return (T)this.context; } public String getId() { return this.id; } public PartitionKey getPartitionKeyValue() { return partitionKey; } public CosmosItemOperationType getOperationType() { return this.operationType; } public RequestOptions getRequestOptions() { return this.requestOptions; } private String getPartitionKeyJson() { return partitionKeyJson; } void setPartitionKeyJson(String value) { partitionKeyJson = value; } BulkOperationRetryPolicy getRetryPolicy() { return bulkOperationRetryPolicy; } void setRetryPolicy(BulkOperationRetryPolicy bulkOperationRetryPolicy) { this.bulkOperationRetryPolicy = bulkOperationRetryPolicy; } @Override public int compareTo(CosmosItemOperation operation) { if (operation instanceof ItemBulkOperation) { ItemBulkOperation<?, ?> bulkOperation = (ItemBulkOperation<?, ?>) operation; return this.index - bulkOperation.index; } return 0; } @Override public boolean equals(Object obj) { return super.equals(obj); } @Override public int hashCode() { return super.hashCode(); } }
class ItemBulkOperation<TInternal, TContext> extends CosmosItemOperationBase implements Comparable<CosmosItemOperation> { private final TInternal item; private final TContext context; private final String id; private final PartitionKey partitionKey; private final CosmosItemOperationType operationType; private final RequestOptions requestOptions; private String partitionKeyJson; private BulkOperationRetryPolicy bulkOperationRetryPolicy; /** index for preserve ordering in Bulk Executor */ private int index; public ItemBulkOperation( CosmosItemOperationType operationType, String id, PartitionKey partitionKey, RequestOptions requestOptions, TInternal item, TContext context) { checkNotNull(operationType, "expected non-null operationType"); this.operationType = operationType; this.partitionKey = partitionKey; this.id = id; this.item = item; this.context = context; this.requestOptions = requestOptions; this.index = 0; } /** * Writes a single operation to JsonSerializable. * TODO(rakkuma): Similarly for hybrid row, operation needs to be written in Hybrid row. * Issue: https: * * @return instance of JsonSerializable containing values for a operation. */ @Override JsonSerializable getSerializedOperationInternal() { final JsonSerializable jsonSerializable = new JsonSerializable(); jsonSerializable.set( BatchRequestResponseConstants.FIELD_OPERATION_TYPE, ModelBridgeInternal.getOperationValueForCosmosItemOperationType(this.getOperationType())); if (StringUtils.isNotEmpty(this.getPartitionKeyJson())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_PARTITION_KEY, this.getPartitionKeyJson()); } if (StringUtils.isNotEmpty(this.getId())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_ID, this.getId()); } if (this.getItemInternal() != null) { if (this.getOperationType() == CosmosItemOperationType.PATCH) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_RESOURCE_BODY, PatchUtil.serializableBatchPatchOperation((CosmosPatchOperations) this.getItemInternal(), this.getRequestOptions())); } else { jsonSerializable.set(BatchRequestResponseConstants.FIELD_RESOURCE_BODY, this.getItemInternal()); } } if (this.getRequestOptions() != null) { RequestOptions requestOptions = this.getRequestOptions(); if (StringUtils.isNotEmpty(requestOptions.getIfMatchETag())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_IF_MATCH, requestOptions.getIfMatchETag()); } if (StringUtils.isNotEmpty(requestOptions.getIfNoneMatchETag())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_IF_NONE_MATCH, requestOptions.getIfNoneMatchETag()); } if (requestOptions.isContentResponseOnWriteEnabled() != null) { if (!requestOptions.isContentResponseOnWriteEnabled() && BulkExecutorUtil.isWriteOperation(operationType)) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_MINIMAL_RETURN_PREFERENCE, true); } } } return jsonSerializable; } public int getIndex() { return index; } TInternal getItemInternal() { return this.item; } @SuppressWarnings("unchecked") public <T> T getItem() { return (T)this.item; } @SuppressWarnings("unchecked") public <T> T getContext() { return (T)this.context; } public String getId() { return this.id; } public PartitionKey getPartitionKeyValue() { return partitionKey; } public CosmosItemOperationType getOperationType() { return this.operationType; } public RequestOptions getRequestOptions() { return this.requestOptions; } private String getPartitionKeyJson() { return partitionKeyJson; } void setPartitionKeyJson(String value) { partitionKeyJson = value; } BulkOperationRetryPolicy getRetryPolicy() { return bulkOperationRetryPolicy; } void setRetryPolicy(BulkOperationRetryPolicy bulkOperationRetryPolicy) { this.bulkOperationRetryPolicy = bulkOperationRetryPolicy; } @Override public int compareTo(CosmosItemOperation operation) { if (operation instanceof ItemBulkOperation) { ItemBulkOperation<?, ?> bulkOperation = (ItemBulkOperation<?, ?>) operation; return this.index - bulkOperation.index; } return 0; } @Override public boolean equals(Object obj) { return super.equals(obj); } @Override public int hashCode() { return super.hashCode(); } }
Can we explicitly set `this.index` to 0 in the constructor - for readability reasons?
public void setIndex(int index) { if (this.index == 0) { this.index = index; } }
if (this.index == 0) {
public void setIndex(int index) { if (this.index == 0) { this.index = index; } }
class ItemBulkOperation<TInternal, TContext> extends CosmosItemOperationBase implements Comparable<CosmosItemOperation> { private final TInternal item; private final TContext context; private final String id; private final PartitionKey partitionKey; private final CosmosItemOperationType operationType; private final RequestOptions requestOptions; private String partitionKeyJson; private BulkOperationRetryPolicy bulkOperationRetryPolicy; /** index for preserve ordering in Bulk Executor */ private int index; public ItemBulkOperation( CosmosItemOperationType operationType, String id, PartitionKey partitionKey, RequestOptions requestOptions, TInternal item, TContext context) { checkNotNull(operationType, "expected non-null operationType"); this.operationType = operationType; this.partitionKey = partitionKey; this.id = id; this.item = item; this.context = context; this.requestOptions = requestOptions; } /** * Writes a single operation to JsonSerializable. * TODO(rakkuma): Similarly for hybrid row, operation needs to be written in Hybrid row. * Issue: https: * * @return instance of JsonSerializable containing values for a operation. */ @Override JsonSerializable getSerializedOperationInternal() { final JsonSerializable jsonSerializable = new JsonSerializable(); jsonSerializable.set( BatchRequestResponseConstants.FIELD_OPERATION_TYPE, ModelBridgeInternal.getOperationValueForCosmosItemOperationType(this.getOperationType())); if (StringUtils.isNotEmpty(this.getPartitionKeyJson())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_PARTITION_KEY, this.getPartitionKeyJson()); } if (StringUtils.isNotEmpty(this.getId())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_ID, this.getId()); } if (this.getItemInternal() != null) { if (this.getOperationType() == CosmosItemOperationType.PATCH) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_RESOURCE_BODY, PatchUtil.serializableBatchPatchOperation((CosmosPatchOperations) this.getItemInternal(), this.getRequestOptions())); } else { jsonSerializable.set(BatchRequestResponseConstants.FIELD_RESOURCE_BODY, this.getItemInternal()); } } if (this.getRequestOptions() != null) { RequestOptions requestOptions = this.getRequestOptions(); if (StringUtils.isNotEmpty(requestOptions.getIfMatchETag())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_IF_MATCH, requestOptions.getIfMatchETag()); } if (StringUtils.isNotEmpty(requestOptions.getIfNoneMatchETag())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_IF_NONE_MATCH, requestOptions.getIfNoneMatchETag()); } if (requestOptions.isContentResponseOnWriteEnabled() != null) { if (!requestOptions.isContentResponseOnWriteEnabled() && BulkExecutorUtil.isWriteOperation(operationType)) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_MINIMAL_RETURN_PREFERENCE, true); } } } return jsonSerializable; } public int getIndex() { return index; } TInternal getItemInternal() { return this.item; } @SuppressWarnings("unchecked") public <T> T getItem() { return (T)this.item; } @SuppressWarnings("unchecked") public <T> T getContext() { return (T)this.context; } public String getId() { return this.id; } public PartitionKey getPartitionKeyValue() { return partitionKey; } public CosmosItemOperationType getOperationType() { return this.operationType; } public RequestOptions getRequestOptions() { return this.requestOptions; } private String getPartitionKeyJson() { return partitionKeyJson; } void setPartitionKeyJson(String value) { partitionKeyJson = value; } BulkOperationRetryPolicy getRetryPolicy() { return bulkOperationRetryPolicy; } void setRetryPolicy(BulkOperationRetryPolicy bulkOperationRetryPolicy) { this.bulkOperationRetryPolicy = bulkOperationRetryPolicy; } @Override public int compareTo(CosmosItemOperation operation) { if (operation instanceof ItemBulkOperation) { ItemBulkOperation<?, ?> bulkOperation = (ItemBulkOperation<?, ?>) operation; return this.index - bulkOperation.index; } return 0; } @Override public boolean equals(Object obj) { return super.equals(obj); } @Override public int hashCode() { return super.hashCode(); } }
class ItemBulkOperation<TInternal, TContext> extends CosmosItemOperationBase implements Comparable<CosmosItemOperation> { private final TInternal item; private final TContext context; private final String id; private final PartitionKey partitionKey; private final CosmosItemOperationType operationType; private final RequestOptions requestOptions; private String partitionKeyJson; private BulkOperationRetryPolicy bulkOperationRetryPolicy; /** index for preserve ordering in Bulk Executor */ private int index; public ItemBulkOperation( CosmosItemOperationType operationType, String id, PartitionKey partitionKey, RequestOptions requestOptions, TInternal item, TContext context) { checkNotNull(operationType, "expected non-null operationType"); this.operationType = operationType; this.partitionKey = partitionKey; this.id = id; this.item = item; this.context = context; this.requestOptions = requestOptions; this.index = 0; } /** * Writes a single operation to JsonSerializable. * TODO(rakkuma): Similarly for hybrid row, operation needs to be written in Hybrid row. * Issue: https: * * @return instance of JsonSerializable containing values for a operation. */ @Override JsonSerializable getSerializedOperationInternal() { final JsonSerializable jsonSerializable = new JsonSerializable(); jsonSerializable.set( BatchRequestResponseConstants.FIELD_OPERATION_TYPE, ModelBridgeInternal.getOperationValueForCosmosItemOperationType(this.getOperationType())); if (StringUtils.isNotEmpty(this.getPartitionKeyJson())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_PARTITION_KEY, this.getPartitionKeyJson()); } if (StringUtils.isNotEmpty(this.getId())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_ID, this.getId()); } if (this.getItemInternal() != null) { if (this.getOperationType() == CosmosItemOperationType.PATCH) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_RESOURCE_BODY, PatchUtil.serializableBatchPatchOperation((CosmosPatchOperations) this.getItemInternal(), this.getRequestOptions())); } else { jsonSerializable.set(BatchRequestResponseConstants.FIELD_RESOURCE_BODY, this.getItemInternal()); } } if (this.getRequestOptions() != null) { RequestOptions requestOptions = this.getRequestOptions(); if (StringUtils.isNotEmpty(requestOptions.getIfMatchETag())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_IF_MATCH, requestOptions.getIfMatchETag()); } if (StringUtils.isNotEmpty(requestOptions.getIfNoneMatchETag())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_IF_NONE_MATCH, requestOptions.getIfNoneMatchETag()); } if (requestOptions.isContentResponseOnWriteEnabled() != null) { if (!requestOptions.isContentResponseOnWriteEnabled() && BulkExecutorUtil.isWriteOperation(operationType)) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_MINIMAL_RETURN_PREFERENCE, true); } } } return jsonSerializable; } public int getIndex() { return index; } TInternal getItemInternal() { return this.item; } @SuppressWarnings("unchecked") public <T> T getItem() { return (T)this.item; } @SuppressWarnings("unchecked") public <T> T getContext() { return (T)this.context; } public String getId() { return this.id; } public PartitionKey getPartitionKeyValue() { return partitionKey; } public CosmosItemOperationType getOperationType() { return this.operationType; } public RequestOptions getRequestOptions() { return this.requestOptions; } private String getPartitionKeyJson() { return partitionKeyJson; } void setPartitionKeyJson(String value) { partitionKeyJson = value; } BulkOperationRetryPolicy getRetryPolicy() { return bulkOperationRetryPolicy; } void setRetryPolicy(BulkOperationRetryPolicy bulkOperationRetryPolicy) { this.bulkOperationRetryPolicy = bulkOperationRetryPolicy; } @Override public int compareTo(CosmosItemOperation operation) { if (operation instanceof ItemBulkOperation) { ItemBulkOperation<?, ?> bulkOperation = (ItemBulkOperation<?, ?>) operation; return this.index - bulkOperation.index; } return 0; } @Override public boolean equals(Object obj) { return super.equals(obj); } @Override public int hashCode() { return super.hashCode(); } }
Added it to constructor and left a comment to explain why we do that check.
public void setIndex(int index) { if (this.index == 0) { this.index = index; } }
if (this.index == 0) {
public void setIndex(int index) { if (this.index == 0) { this.index = index; } }
class ItemBulkOperation<TInternal, TContext> extends CosmosItemOperationBase implements Comparable<CosmosItemOperation> { private final TInternal item; private final TContext context; private final String id; private final PartitionKey partitionKey; private final CosmosItemOperationType operationType; private final RequestOptions requestOptions; private String partitionKeyJson; private BulkOperationRetryPolicy bulkOperationRetryPolicy; /** index for preserve ordering in Bulk Executor */ private int index; public ItemBulkOperation( CosmosItemOperationType operationType, String id, PartitionKey partitionKey, RequestOptions requestOptions, TInternal item, TContext context) { checkNotNull(operationType, "expected non-null operationType"); this.operationType = operationType; this.partitionKey = partitionKey; this.id = id; this.item = item; this.context = context; this.requestOptions = requestOptions; } /** * Writes a single operation to JsonSerializable. * TODO(rakkuma): Similarly for hybrid row, operation needs to be written in Hybrid row. * Issue: https: * * @return instance of JsonSerializable containing values for a operation. */ @Override JsonSerializable getSerializedOperationInternal() { final JsonSerializable jsonSerializable = new JsonSerializable(); jsonSerializable.set( BatchRequestResponseConstants.FIELD_OPERATION_TYPE, ModelBridgeInternal.getOperationValueForCosmosItemOperationType(this.getOperationType())); if (StringUtils.isNotEmpty(this.getPartitionKeyJson())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_PARTITION_KEY, this.getPartitionKeyJson()); } if (StringUtils.isNotEmpty(this.getId())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_ID, this.getId()); } if (this.getItemInternal() != null) { if (this.getOperationType() == CosmosItemOperationType.PATCH) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_RESOURCE_BODY, PatchUtil.serializableBatchPatchOperation((CosmosPatchOperations) this.getItemInternal(), this.getRequestOptions())); } else { jsonSerializable.set(BatchRequestResponseConstants.FIELD_RESOURCE_BODY, this.getItemInternal()); } } if (this.getRequestOptions() != null) { RequestOptions requestOptions = this.getRequestOptions(); if (StringUtils.isNotEmpty(requestOptions.getIfMatchETag())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_IF_MATCH, requestOptions.getIfMatchETag()); } if (StringUtils.isNotEmpty(requestOptions.getIfNoneMatchETag())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_IF_NONE_MATCH, requestOptions.getIfNoneMatchETag()); } if (requestOptions.isContentResponseOnWriteEnabled() != null) { if (!requestOptions.isContentResponseOnWriteEnabled() && BulkExecutorUtil.isWriteOperation(operationType)) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_MINIMAL_RETURN_PREFERENCE, true); } } } return jsonSerializable; } public int getIndex() { return index; } TInternal getItemInternal() { return this.item; } @SuppressWarnings("unchecked") public <T> T getItem() { return (T)this.item; } @SuppressWarnings("unchecked") public <T> T getContext() { return (T)this.context; } public String getId() { return this.id; } public PartitionKey getPartitionKeyValue() { return partitionKey; } public CosmosItemOperationType getOperationType() { return this.operationType; } public RequestOptions getRequestOptions() { return this.requestOptions; } private String getPartitionKeyJson() { return partitionKeyJson; } void setPartitionKeyJson(String value) { partitionKeyJson = value; } BulkOperationRetryPolicy getRetryPolicy() { return bulkOperationRetryPolicy; } void setRetryPolicy(BulkOperationRetryPolicy bulkOperationRetryPolicy) { this.bulkOperationRetryPolicy = bulkOperationRetryPolicy; } @Override public int compareTo(CosmosItemOperation operation) { if (operation instanceof ItemBulkOperation) { ItemBulkOperation<?, ?> bulkOperation = (ItemBulkOperation<?, ?>) operation; return this.index - bulkOperation.index; } return 0; } @Override public boolean equals(Object obj) { return super.equals(obj); } @Override public int hashCode() { return super.hashCode(); } }
class ItemBulkOperation<TInternal, TContext> extends CosmosItemOperationBase implements Comparable<CosmosItemOperation> { private final TInternal item; private final TContext context; private final String id; private final PartitionKey partitionKey; private final CosmosItemOperationType operationType; private final RequestOptions requestOptions; private String partitionKeyJson; private BulkOperationRetryPolicy bulkOperationRetryPolicy; /** index for preserve ordering in Bulk Executor */ private int index; public ItemBulkOperation( CosmosItemOperationType operationType, String id, PartitionKey partitionKey, RequestOptions requestOptions, TInternal item, TContext context) { checkNotNull(operationType, "expected non-null operationType"); this.operationType = operationType; this.partitionKey = partitionKey; this.id = id; this.item = item; this.context = context; this.requestOptions = requestOptions; this.index = 0; } /** * Writes a single operation to JsonSerializable. * TODO(rakkuma): Similarly for hybrid row, operation needs to be written in Hybrid row. * Issue: https: * * @return instance of JsonSerializable containing values for a operation. */ @Override JsonSerializable getSerializedOperationInternal() { final JsonSerializable jsonSerializable = new JsonSerializable(); jsonSerializable.set( BatchRequestResponseConstants.FIELD_OPERATION_TYPE, ModelBridgeInternal.getOperationValueForCosmosItemOperationType(this.getOperationType())); if (StringUtils.isNotEmpty(this.getPartitionKeyJson())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_PARTITION_KEY, this.getPartitionKeyJson()); } if (StringUtils.isNotEmpty(this.getId())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_ID, this.getId()); } if (this.getItemInternal() != null) { if (this.getOperationType() == CosmosItemOperationType.PATCH) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_RESOURCE_BODY, PatchUtil.serializableBatchPatchOperation((CosmosPatchOperations) this.getItemInternal(), this.getRequestOptions())); } else { jsonSerializable.set(BatchRequestResponseConstants.FIELD_RESOURCE_BODY, this.getItemInternal()); } } if (this.getRequestOptions() != null) { RequestOptions requestOptions = this.getRequestOptions(); if (StringUtils.isNotEmpty(requestOptions.getIfMatchETag())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_IF_MATCH, requestOptions.getIfMatchETag()); } if (StringUtils.isNotEmpty(requestOptions.getIfNoneMatchETag())) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_IF_NONE_MATCH, requestOptions.getIfNoneMatchETag()); } if (requestOptions.isContentResponseOnWriteEnabled() != null) { if (!requestOptions.isContentResponseOnWriteEnabled() && BulkExecutorUtil.isWriteOperation(operationType)) { jsonSerializable.set(BatchRequestResponseConstants.FIELD_MINIMAL_RETURN_PREFERENCE, true); } } } return jsonSerializable; } public int getIndex() { return index; } TInternal getItemInternal() { return this.item; } @SuppressWarnings("unchecked") public <T> T getItem() { return (T)this.item; } @SuppressWarnings("unchecked") public <T> T getContext() { return (T)this.context; } public String getId() { return this.id; } public PartitionKey getPartitionKeyValue() { return partitionKey; } public CosmosItemOperationType getOperationType() { return this.operationType; } public RequestOptions getRequestOptions() { return this.requestOptions; } private String getPartitionKeyJson() { return partitionKeyJson; } void setPartitionKeyJson(String value) { partitionKeyJson = value; } BulkOperationRetryPolicy getRetryPolicy() { return bulkOperationRetryPolicy; } void setRetryPolicy(BulkOperationRetryPolicy bulkOperationRetryPolicy) { this.bulkOperationRetryPolicy = bulkOperationRetryPolicy; } @Override public int compareTo(CosmosItemOperation operation) { if (operation instanceof ItemBulkOperation) { ItemBulkOperation<?, ?> bulkOperation = (ItemBulkOperation<?, ?>) operation; return this.index - bulkOperation.index; } return 0; } @Override public boolean equals(Object obj) { return super.equals(obj); } @Override public int hashCode() { return super.hashCode(); } }
oh Interesting, does this mean that the JSON for the requests/reponses will start showing up in standard output for tests?
OpenAIClientBuilder getOpenAIClientBuilder(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { OpenAIClientBuilder builder = new OpenAIClientBuilder() .httpClient(httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (getTestMode() == TestMode.PLAYBACK) { builder .endpoint("https: .credential(new AzureKeyCredential(FAKE_API_KEY)); } else if (getTestMode() == TestMode.RECORD) { builder .addPolicy(interceptorManager.getRecordPolicy()) .endpoint(Configuration.getGlobalConfiguration().get("AZURE_OPENAI_ENDPOINT")) .credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_OPENAI_KEY"))); } else { builder .endpoint(Configuration.getGlobalConfiguration().get("AZURE_OPENAI_ENDPOINT")) .credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_OPENAI_KEY"))); } return builder; }
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
OpenAIClientBuilder getOpenAIClientBuilder(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { OpenAIClientBuilder builder = new OpenAIClientBuilder() .httpClient(httpClient) .serviceVersion(serviceVersion); if (getTestMode() == TestMode.PLAYBACK) { builder .endpoint("https: .credential(new AzureKeyCredential(FAKE_API_KEY)); } else if (getTestMode() == TestMode.RECORD) { builder .addPolicy(interceptorManager.getRecordPolicy()) .endpoint(Configuration.getGlobalConfiguration().get("AZURE_OPENAI_ENDPOINT")) .credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_OPENAI_KEY"))); } else { builder .endpoint(Configuration.getGlobalConfiguration().get("AZURE_OPENAI_ENDPOINT")) .credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_OPENAI_KEY"))); } return builder; }
class OpenAIClientTestBase extends TestProxyTestBase { OpenAIClientBuilder getNonAzureOpenAIClientBuilder(HttpClient httpClient) { OpenAIClientBuilder builder = new OpenAIClientBuilder() .httpClient(httpClient); if (getTestMode() == TestMode.PLAYBACK) { builder .credential(new NonAzureOpenAIKeyCredential(FAKE_API_KEY)); } else if (getTestMode() == TestMode.RECORD) { builder .addPolicy(interceptorManager.getRecordPolicy()) .credential(new NonAzureOpenAIKeyCredential(Configuration.getGlobalConfiguration().get("NON_AZURE_OPENAI_KEY"))); } else { builder .credential(new NonAzureOpenAIKeyCredential(Configuration.getGlobalConfiguration().get("NON_AZURE_OPENAI_KEY"))); } return builder; } @Test public abstract void testGetCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetChatCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetChatCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetEmbeddings(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetEmbeddingsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion); void getCompletionsRunner(BiConsumer<String, List<String>> testRunner) { String deploymentId = "text-davinci-003"; List<String> prompt = new ArrayList<>(); prompt.add("Say this is a test"); testRunner.accept(deploymentId, prompt); } void getCompletionsFromSinglePromptRunner(BiConsumer<String, String> testRunner) { String deploymentId = "text-davinci-003"; String prompt = "Say this is a test"; testRunner.accept(deploymentId, prompt); } void getChatCompletionsRunner(BiConsumer<String, List<ChatMessage>> testRunner) { testRunner.accept("gpt-35-turbo", getChatMessages()); } void getChatCompletionsForNonAzureRunner(BiConsumer<String, List<ChatMessage>> testRunner) { testRunner.accept("gpt-3.5-turbo", getChatMessages()); } void getEmbeddingRunner(BiConsumer<String, EmbeddingsOptions> testRunner) { testRunner.accept("text-embedding-ada-002", new EmbeddingsOptions(Arrays.asList("Your text string goes here"))); } void getEmbeddingNonAzureRunner(BiConsumer<String, EmbeddingsOptions> testRunner) { testRunner.accept("text-embedding-ada-002", new EmbeddingsOptions(Arrays.asList("Your text string goes here"))); } void getImageGenerationRunner(Consumer<ImageGenerationOptions> testRunner) { testRunner.accept( new ImageGenerationOptions("A drawing of the Seattle skyline in the style of Van Gogh") ); } void getChatFunctionForNonAzureRunner(BiConsumer<String, ChatCompletionsOptions> testRunner) { testRunner.accept("gpt-3.5-turbo-0613", getChatMessagesWithFunction()); } void getChatFunctionForRunner(BiConsumer<String, ChatCompletionsOptions> testRunner) { testRunner.accept("gpt-4", getChatMessagesWithFunction()); } private List<ChatMessage> getChatMessages() { List<ChatMessage> chatMessages = new ArrayList<>(); chatMessages.add(new ChatMessage(ChatRole.SYSTEM).setContent("You are a helpful assistant. You will talk like a pirate.")); chatMessages.add(new ChatMessage(ChatRole.USER).setContent("Can you help me?")); chatMessages.add(new ChatMessage(ChatRole.ASSISTANT).setContent("Of course, me hearty! What can I do for ye?")); chatMessages.add(new ChatMessage(ChatRole.USER).setContent("What's the best way to train a parrot?")); return chatMessages; } private ChatCompletionsOptions getChatMessagesWithFunction() { FunctionDefinition functionDefinition = new FunctionDefinition("MyFunction"); Parameters parameters = new Parameters(); functionDefinition.setParameters(parameters); List<FunctionDefinition> functions = Arrays.asList(functionDefinition); List<ChatMessage> chatMessages = new ArrayList<>(); chatMessages.add(new ChatMessage(ChatRole.USER).setContent("What's the weather like in San Francisco in Celsius?")); ChatCompletionsOptions chatCompletionOptions = new ChatCompletionsOptions(chatMessages); chatCompletionOptions.setFunctions(functions); return chatCompletionOptions; } static void assertCompletions(int choicesPerPrompt, Completions actual) { assertCompletions(choicesPerPrompt, "stop", actual); } static void assertCompletions(int choicesPerPrompt, String expectedFinishReason, Completions actual) { assertNotNull(actual); assertInstanceOf(Completions.class, actual); assertChoices(choicesPerPrompt, expectedFinishReason, actual.getChoices()); assertNotNull(actual.getUsage()); } static <T> T assertAndGetValueFromResponse(Response<BinaryData> actualResponse, Class<T> clazz, int expectedCode) { assertNotNull(actualResponse); assertEquals(expectedCode, actualResponse.getStatusCode()); assertInstanceOf(Response.class, actualResponse); BinaryData binaryData = actualResponse.getValue(); assertNotNull(binaryData); T object = binaryData.toObject(clazz); assertNotNull(object); assertInstanceOf(clazz, object); return object; } static void assertChoices(int choicesPerPrompt, String expectedFinishReason, List<Choice> actual) { assertEquals(choicesPerPrompt, actual.size()); for (int i = 0; i < actual.size(); i++) { assertChoice(i, expectedFinishReason, actual.get(i)); } } static void assertChoice(int index, String expectedFinishReason, Choice actual) { assertNotNull(actual.getText()); assertEquals(index, actual.getIndex()); assertEquals(expectedFinishReason, actual.getFinishReason().toString()); } static void assertChatCompletions(int choiceCount, ChatCompletions actual) { List<ChatChoice> choices = actual.getChoices(); assertNotNull(choices); assertTrue(choices.size() > 0); assertChatChoices(choiceCount, "stop", ChatRole.ASSISTANT, choices); assertNotNull(actual.getUsage()); } static void assertChatCompletionsStream(ChatCompletions chatCompletions) { if (chatCompletions.getId() != null && !chatCompletions.getId().isEmpty()) { assertNotNull(chatCompletions.getId()); assertNotNull(chatCompletions.getChoices()); assertFalse(chatCompletions.getChoices().isEmpty()); assertNotNull(chatCompletions.getChoices().get(0).getDelta()); } } static void assertCompletionsStream(Completions completions) { if (completions.getId() != null && !completions.getId().isEmpty()) { assertNotNull(completions.getId()); assertNotNull(completions.getChoices()); assertFalse(completions.getChoices().isEmpty()); assertNotNull(completions.getChoices().get(0).getText()); } } static void assertChatCompletions(int choiceCount, String expectedFinishReason, ChatRole chatRole, ChatCompletions actual) { List<ChatChoice> choices = actual.getChoices(); assertNotNull(choices); assertTrue(choices.size() > 0); assertChatChoices(choiceCount, expectedFinishReason, chatRole, choices); assertNotNull(actual.getUsage()); } static void assertChatChoices(int choiceCount, String expectedFinishReason, ChatRole chatRole, List<ChatChoice> actual) { assertEquals(choiceCount, actual.size()); for (int i = 0; i < actual.size(); i++) { assertChatChoice(i, expectedFinishReason, chatRole, actual.get(i)); } } static void assertChatChoice(int index, String expectedFinishReason, ChatRole chatRole, ChatChoice actual) { assertEquals(index, actual.getIndex()); assertEquals(chatRole, actual.getMessage().getRole()); assertNotNull(actual.getMessage().getContent()); assertEquals(expectedFinishReason, actual.getFinishReason().toString()); } static void assertEmbeddings(Embeddings actual) { List<EmbeddingItem> data = actual.getData(); assertNotNull(data); assertTrue(data.size() > 0); for (EmbeddingItem item : data) { List<Double> embedding = item.getEmbedding(); assertNotNull(embedding); assertTrue(embedding.size() > 0); } assertNotNull(actual.getUsage()); } static void assertImageResponse(ImageResponse actual) { assertNotNull(actual.getData()); assertFalse(actual.getData().isEmpty()); } static <T> T assertFunctionCall(ChatChoice actual, String functionName, Class<T> myPropertiesClazz) { assertEquals(0, actual.getIndex()); assertEquals("function_call", actual.getFinishReason().toString()); FunctionCall functionCall = actual.getMessage().getFunctionCall(); assertEquals(functionName, functionCall.getName()); BinaryData argumentJson = BinaryData.fromString(functionCall.getArguments()); return argumentJson.toObject(myPropertiesClazz); } }
class OpenAIClientTestBase extends TestProxyTestBase { OpenAIClientBuilder getNonAzureOpenAIClientBuilder(HttpClient httpClient) { OpenAIClientBuilder builder = new OpenAIClientBuilder() .httpClient(httpClient); if (getTestMode() == TestMode.PLAYBACK) { builder .credential(new NonAzureOpenAIKeyCredential(FAKE_API_KEY)); } else if (getTestMode() == TestMode.RECORD) { builder .addPolicy(interceptorManager.getRecordPolicy()) .credential(new NonAzureOpenAIKeyCredential(Configuration.getGlobalConfiguration().get("NON_AZURE_OPENAI_KEY"))); } else { builder .credential(new NonAzureOpenAIKeyCredential(Configuration.getGlobalConfiguration().get("NON_AZURE_OPENAI_KEY"))); } return builder; } @Test public abstract void testGetCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetChatCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetChatCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetEmbeddings(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetEmbeddingsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion); void getCompletionsRunner(BiConsumer<String, List<String>> testRunner) { String deploymentId = "text-davinci-003"; List<String> prompt = new ArrayList<>(); prompt.add("Say this is a test"); testRunner.accept(deploymentId, prompt); } void getCompletionsFromSinglePromptRunner(BiConsumer<String, String> testRunner) { String deploymentId = "text-davinci-003"; String prompt = "Say this is a test"; testRunner.accept(deploymentId, prompt); } void getChatCompletionsRunner(BiConsumer<String, List<ChatMessage>> testRunner) { testRunner.accept("gpt-35-turbo", getChatMessages()); } void getChatCompletionsForNonAzureRunner(BiConsumer<String, List<ChatMessage>> testRunner) { testRunner.accept("gpt-3.5-turbo", getChatMessages()); } void getEmbeddingRunner(BiConsumer<String, EmbeddingsOptions> testRunner) { testRunner.accept("text-embedding-ada-002", new EmbeddingsOptions(Arrays.asList("Your text string goes here"))); } void getEmbeddingNonAzureRunner(BiConsumer<String, EmbeddingsOptions> testRunner) { testRunner.accept("text-embedding-ada-002", new EmbeddingsOptions(Arrays.asList("Your text string goes here"))); } void getImageGenerationRunner(Consumer<ImageGenerationOptions> testRunner) { testRunner.accept( new ImageGenerationOptions("A drawing of the Seattle skyline in the style of Van Gogh") ); } void getChatFunctionForNonAzureRunner(BiConsumer<String, ChatCompletionsOptions> testRunner) { testRunner.accept("gpt-3.5-turbo-0613", getChatMessagesWithFunction()); } void getChatFunctionForRunner(BiConsumer<String, ChatCompletionsOptions> testRunner) { testRunner.accept("gpt-4", getChatMessagesWithFunction()); } void getChatCompletionsContentFilterRunner(BiConsumer<String, List<ChatMessage>> testRunner) { testRunner.accept("gpt-4", getChatMessages()); } void getCompletionsContentFilterRunner(BiConsumer<String, String> testRunner) { testRunner.accept("gpt-35-turbo", "What is 3 times 4?"); } void getChatCompletionsContentFilterRunnerForNonAzure(BiConsumer<String, List<ChatMessage>> testRunner) { testRunner.accept("gpt-3.5-turbo-0613", getChatMessages()); } void getCompletionsContentFilterRunnerForNonAzure(BiConsumer<String, String> testRunner) { testRunner.accept("text-davinci-002", "What is 3 times 4?"); } private List<ChatMessage> getChatMessages() { List<ChatMessage> chatMessages = new ArrayList<>(); chatMessages.add(new ChatMessage(ChatRole.SYSTEM).setContent("You are a helpful assistant. You will talk like a pirate.")); chatMessages.add(new ChatMessage(ChatRole.USER).setContent("Can you help me?")); chatMessages.add(new ChatMessage(ChatRole.ASSISTANT).setContent("Of course, me hearty! What can I do for ye?")); chatMessages.add(new ChatMessage(ChatRole.USER).setContent("What's the best way to train a parrot?")); return chatMessages; } private ChatCompletionsOptions getChatMessagesWithFunction() { FunctionDefinition functionDefinition = new FunctionDefinition("MyFunction"); Parameters parameters = new Parameters(); functionDefinition.setParameters(parameters); List<FunctionDefinition> functions = Arrays.asList(functionDefinition); List<ChatMessage> chatMessages = new ArrayList<>(); chatMessages.add(new ChatMessage(ChatRole.USER).setContent("What's the weather like in San Francisco in Celsius?")); ChatCompletionsOptions chatCompletionOptions = new ChatCompletionsOptions(chatMessages); chatCompletionOptions.setFunctions(functions); return chatCompletionOptions; } static void assertCompletions(int choicesPerPrompt, Completions actual) { assertCompletions(choicesPerPrompt, "stop", actual); } static void assertCompletions(int choicesPerPrompt, String expectedFinishReason, Completions actual) { assertNotNull(actual); assertInstanceOf(Completions.class, actual); assertChoices(choicesPerPrompt, expectedFinishReason, actual.getChoices()); assertNotNull(actual.getUsage()); } static <T> T assertAndGetValueFromResponse(Response<BinaryData> actualResponse, Class<T> clazz, int expectedCode) { assertNotNull(actualResponse); assertEquals(expectedCode, actualResponse.getStatusCode()); assertInstanceOf(Response.class, actualResponse); BinaryData binaryData = actualResponse.getValue(); assertNotNull(binaryData); T object = binaryData.toObject(clazz); assertNotNull(object); assertInstanceOf(clazz, object); return object; } static void assertChoices(int choicesPerPrompt, String expectedFinishReason, List<Choice> actual) { assertEquals(choicesPerPrompt, actual.size()); for (int i = 0; i < actual.size(); i++) { assertChoice(i, expectedFinishReason, actual.get(i)); } } static void assertChoice(int index, String expectedFinishReason, Choice actual) { assertNotNull(actual.getText()); assertEquals(index, actual.getIndex()); assertEquals(expectedFinishReason, actual.getFinishReason().toString()); } static void assertChatCompletions(int choiceCount, ChatCompletions actual) { List<ChatChoice> choices = actual.getChoices(); assertNotNull(choices); assertTrue(choices.size() > 0); assertChatChoices(choiceCount, "stop", ChatRole.ASSISTANT, choices); assertNotNull(actual.getUsage()); } static void assertChatCompletionsStream(ChatCompletions chatCompletions) { if (chatCompletions.getId() != null && !chatCompletions.getId().isEmpty()) { assertNotNull(chatCompletions.getId()); assertNotNull(chatCompletions.getChoices()); assertFalse(chatCompletions.getChoices().isEmpty()); assertNotNull(chatCompletions.getChoices().get(0).getDelta()); } } static void assertCompletionsStream(Completions completions) { if (completions.getId() != null && !completions.getId().isEmpty()) { assertNotNull(completions.getId()); assertNotNull(completions.getChoices()); assertFalse(completions.getChoices().isEmpty()); assertNotNull(completions.getChoices().get(0).getText()); } } static void assertChatCompletions(int choiceCount, String expectedFinishReason, ChatRole chatRole, ChatCompletions actual) { List<ChatChoice> choices = actual.getChoices(); assertNotNull(choices); assertTrue(choices.size() > 0); assertChatChoices(choiceCount, expectedFinishReason, chatRole, choices); assertNotNull(actual.getUsage()); } static void assertChatChoices(int choiceCount, String expectedFinishReason, ChatRole chatRole, List<ChatChoice> actual) { assertEquals(choiceCount, actual.size()); for (int i = 0; i < actual.size(); i++) { assertChatChoice(i, expectedFinishReason, chatRole, actual.get(i)); } } static void assertChatChoice(int index, String expectedFinishReason, ChatRole chatRole, ChatChoice actual) { assertEquals(index, actual.getIndex()); assertEquals(chatRole, actual.getMessage().getRole()); assertNotNull(actual.getMessage().getContent()); assertEquals(expectedFinishReason, actual.getFinishReason().toString()); } static void assertEmbeddings(Embeddings actual) { List<EmbeddingItem> data = actual.getData(); assertNotNull(data); assertTrue(data.size() > 0); for (EmbeddingItem item : data) { List<Double> embedding = item.getEmbedding(); assertNotNull(embedding); assertTrue(embedding.size() > 0); } assertNotNull(actual.getUsage()); } static void assertImageResponse(ImageResponse actual) { assertNotNull(actual.getData()); assertFalse(actual.getData().isEmpty()); } static <T> T assertFunctionCall(ChatChoice actual, String functionName, Class<T> myPropertiesClazz) { assertEquals(0, actual.getIndex()); assertEquals("function_call", actual.getFinishReason().toString()); FunctionCall functionCall = actual.getMessage().getFunctionCall(); assertEquals(functionName, functionCall.getName()); BinaryData argumentJson = BinaryData.fromString(functionCall.getArguments()); return argumentJson.toObject(myPropertiesClazz); } static void assertSafeContentFilterResults(ContentFilterResults contentFilterResults) { assertNotNull(contentFilterResults); assertFalse(contentFilterResults.getHate().isFiltered()); assertEquals(contentFilterResults.getHate().getSeverity(), ContentFilterSeverity.SAFE); assertFalse(contentFilterResults.getSexual().isFiltered()); assertEquals(contentFilterResults.getSexual().getSeverity(), ContentFilterSeverity.SAFE); assertFalse(contentFilterResults.getSelfHarm().isFiltered()); assertEquals(contentFilterResults.getSelfHarm().getSeverity(), ContentFilterSeverity.SAFE); assertFalse(contentFilterResults.getViolence().isFiltered()); assertEquals(contentFilterResults.getViolence().getSeverity(), ContentFilterSeverity.SAFE); } }
Could you explain what `Exceptions.unwrap` if for and the usage of `LOGGER` here? I am not entirely sure I understand why this is done like this. I though you could simply do: ```java try { // blocking call } catch (Exception e) { throw new RuntimeException(e); } ```
public ImageResponse getImages(ImageGenerationOptions imageGenerationOptions) { RequestOptions requestOptions = new RequestOptions(); BinaryData imageGenerationOptionsBinaryData = BinaryData.fromObject(imageGenerationOptions); if (openAIServiceClient != null) { return openAIServiceClient .generateImageWithResponse(imageGenerationOptionsBinaryData, requestOptions) .getValue() .toObject(ImageResponse.class); } else { try { return this.serviceClient.beginBeginAzureBatchImageGenerationAsync(imageGenerationOptionsBinaryData, requestOptions) .last() .flatMap(it -> it.getFinalResult()) .map(it -> it.toObject(ImageOperationResponse.class).getResult()).block(); } catch (Exception e) { Throwable unwrapped = Exceptions.unwrap(e); if (unwrapped instanceof RuntimeException) { throw LOGGER.logExceptionAsError((RuntimeException) unwrapped); } else if (unwrapped instanceof IOException) { throw LOGGER.logExceptionAsError(new UncheckedIOException((IOException) unwrapped)); } else { throw LOGGER.logExceptionAsError(new RuntimeException(unwrapped)); } } } }
}
public ImageResponse getImages(ImageGenerationOptions imageGenerationOptions) { RequestOptions requestOptions = new RequestOptions(); BinaryData imageGenerationOptionsBinaryData = BinaryData.fromObject(imageGenerationOptions); if (openAIServiceClient != null) { return openAIServiceClient .generateImageWithResponse(imageGenerationOptionsBinaryData, requestOptions) .getValue() .toObject(ImageResponse.class); } else { try { return this.serviceClient.beginBeginAzureBatchImageGenerationAsync(imageGenerationOptionsBinaryData, requestOptions) .last() .flatMap(it -> it.getFinalResult()) .map(it -> it.toObject(ImageOperationResponse.class).getResult()).block(); } catch (Exception e) { Throwable unwrapped = Exceptions.unwrap(e); if (unwrapped instanceof RuntimeException) { throw LOGGER.logExceptionAsError((RuntimeException) unwrapped); } else if (unwrapped instanceof IOException) { throw LOGGER.logExceptionAsError(new UncheckedIOException((IOException) unwrapped)); } else { throw LOGGER.logExceptionAsError(new RuntimeException(unwrapped)); } } } }
class for NonAzure Implementation. * * @param serviceClient the service client implementation. */ OpenAIClient(NonAzureOpenAIClientImpl serviceClient) { this.serviceClient = null; openAIServiceClient = serviceClient; }
class for NonAzure Implementation. * * @param serviceClient the service client implementation. */ OpenAIClient(NonAzureOpenAIClientImpl serviceClient) { this.serviceClient = null; openAIServiceClient = serviceClient; }
This should already be redacting, is it not?
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( MapsRenderClientBuilder.RENDER_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER)));
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode() || interceptorManager.isPlaybackMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( MapsRenderClientBuilder.RENDER_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
class MapsRenderClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } MapsRenderClientBuilder getRenderAsyncClientBuilder(HttpClient httpClient, MapsRenderServiceVersion serviceVersion) { MapsRenderClientBuilder builder = new MapsRenderClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetMapTile(byte[] actual) { assertNotNull(actual); assertTrue(actual.length > 0); } static void validateGetMapTileWithResponse(int expectedStatusCode, Response<BinaryData> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapTile(response.getValue().toBytes()); } static void validateGetMapTileset(MapTileset expected, MapTileset actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getMinZoom(), actual.getMinZoom()); } static void validateGetMapTilesetWithResponse(MapTileset expected, int expectedStatusCode, Response<MapTileset> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapTileset(expected, response.getValue()); } static void validateGetMapAttribution(MapAttribution expected, MapAttribution actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCopyrights().size(), actual.getCopyrights().size()); } static void validateGetMapAttributionWithResponse(MapAttribution expected, int expectedStatusCode, Response<MapAttribution> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapAttribution(expected, response.getValue()); } static void validateGetCopyrightCaption(CopyrightCaption expected, CopyrightCaption actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); } static void validateGetCopyrightCaptionWithResponse(CopyrightCaption expected, int expectedStatusCode, Response<CopyrightCaption> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightCaption(expected, response.getValue()); } static void validateGetCopyrightCaptionFromBoundingBox(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); assertEquals(expected.getRegions().size(), actual.getRegions().size()); } static void validateGetCopyrightCaptionFromBoundingBoxWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightCaptionFromBoundingBox(expected, response.getValue()); } static void validateGetMapStaticImage(byte[] actual) { assertNotNull(actual); assertTrue(actual.length > 0); } static void validateGetMapStaticImageWithResponse(int expectedStatusCode, Response<BinaryData> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapStaticImage(response.getValue().toBytes()); } static void validateGetCopyrightForTile(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); assertEquals(expected.getRegions().size(), actual.getRegions().size()); } static void validateGetCopyrightForTileWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightForTile(expected, response.getValue()); } static void validateGetCopyrightForWorld(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); } static void validateGetCopyrightForWorldWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightForWorld(expected, response.getValue()); } }
class MapsRenderClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } MapsRenderClientBuilder getRenderAsyncClientBuilder(HttpClient httpClient, MapsRenderServiceVersion serviceVersion) { MapsRenderClientBuilder builder = new MapsRenderClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetMapTile(byte[] actual) { assertNotNull(actual); assertTrue(actual.length > 0); } static void validateGetMapTileWithResponse(int expectedStatusCode, Response<BinaryData> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapTile(response.getValue().toBytes()); } static void validateGetMapTileset(MapTileset expected, MapTileset actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getMinZoom(), actual.getMinZoom()); } static void validateGetMapTilesetWithResponse(MapTileset expected, int expectedStatusCode, Response<MapTileset> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapTileset(expected, response.getValue()); } static void validateGetMapAttribution(MapAttribution expected, MapAttribution actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCopyrights().size(), actual.getCopyrights().size()); } static void validateGetMapAttributionWithResponse(MapAttribution expected, int expectedStatusCode, Response<MapAttribution> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapAttribution(expected, response.getValue()); } static void validateGetCopyrightCaption(CopyrightCaption expected, CopyrightCaption actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); } static void validateGetCopyrightCaptionWithResponse(CopyrightCaption expected, int expectedStatusCode, Response<CopyrightCaption> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightCaption(expected, response.getValue()); } static void validateGetCopyrightCaptionFromBoundingBox(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); assertEquals(expected.getRegions().size(), actual.getRegions().size()); } static void validateGetCopyrightCaptionFromBoundingBoxWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightCaptionFromBoundingBox(expected, response.getValue()); } static void validateGetMapStaticImage(byte[] actual) { assertNotNull(actual); assertTrue(actual.length > 0); } static void validateGetMapStaticImageWithResponse(int expectedStatusCode, Response<BinaryData> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapStaticImage(response.getValue().toBytes()); } static void validateGetCopyrightForTile(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); assertEquals(expected.getRegions().size(), actual.getRegions().size()); } static void validateGetCopyrightForTileWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightForTile(expected, response.getValue()); } static void validateGetCopyrightForWorld(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); } static void validateGetCopyrightForWorldWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightForWorld(expected, response.getValue()); } }
Reactor offers [Exceptions.unwrap](https://projectreactor.io/docs/core/release/api/reactor/core/Exceptions.html#unwrap-java.lang.Throwable-) which should unwrap the exceptions bubbled up through the stream to what was thrown. This could help us remove all the exception stack trace information that is mostly/entirely Reactor and help make it easier to debug issues that happen. we can't throw directly, it will break our checkstyle check: Directly throwing an exception is disallowed. Must throw through "ClientLogger" API, either of "logger.logExceptionAsError", "logger.logThrowableAsError", "logger.atError().log", "logger.logExceptionAsWarning", "logger.logThrowableAsWarning", or "logger.atWarning().log" where "logger" is type of ClientLogger from Azure Core package. [ThrowFromClientLogger]
public ImageResponse getImages(ImageGenerationOptions imageGenerationOptions) { RequestOptions requestOptions = new RequestOptions(); BinaryData imageGenerationOptionsBinaryData = BinaryData.fromObject(imageGenerationOptions); if (openAIServiceClient != null) { return openAIServiceClient .generateImageWithResponse(imageGenerationOptionsBinaryData, requestOptions) .getValue() .toObject(ImageResponse.class); } else { try { return this.serviceClient.beginBeginAzureBatchImageGenerationAsync(imageGenerationOptionsBinaryData, requestOptions) .last() .flatMap(it -> it.getFinalResult()) .map(it -> it.toObject(ImageOperationResponse.class).getResult()).block(); } catch (Exception e) { Throwable unwrapped = Exceptions.unwrap(e); if (unwrapped instanceof RuntimeException) { throw LOGGER.logExceptionAsError((RuntimeException) unwrapped); } else if (unwrapped instanceof IOException) { throw LOGGER.logExceptionAsError(new UncheckedIOException((IOException) unwrapped)); } else { throw LOGGER.logExceptionAsError(new RuntimeException(unwrapped)); } } } }
}
public ImageResponse getImages(ImageGenerationOptions imageGenerationOptions) { RequestOptions requestOptions = new RequestOptions(); BinaryData imageGenerationOptionsBinaryData = BinaryData.fromObject(imageGenerationOptions); if (openAIServiceClient != null) { return openAIServiceClient .generateImageWithResponse(imageGenerationOptionsBinaryData, requestOptions) .getValue() .toObject(ImageResponse.class); } else { try { return this.serviceClient.beginBeginAzureBatchImageGenerationAsync(imageGenerationOptionsBinaryData, requestOptions) .last() .flatMap(it -> it.getFinalResult()) .map(it -> it.toObject(ImageOperationResponse.class).getResult()).block(); } catch (Exception e) { Throwable unwrapped = Exceptions.unwrap(e); if (unwrapped instanceof RuntimeException) { throw LOGGER.logExceptionAsError((RuntimeException) unwrapped); } else if (unwrapped instanceof IOException) { throw LOGGER.logExceptionAsError(new UncheckedIOException((IOException) unwrapped)); } else { throw LOGGER.logExceptionAsError(new RuntimeException(unwrapped)); } } } }
class for NonAzure Implementation. * * @param serviceClient the service client implementation. */ OpenAIClient(NonAzureOpenAIClientImpl serviceClient) { this.serviceClient = null; openAIServiceClient = serviceClient; }
class for NonAzure Implementation. * * @param serviceClient the service client implementation. */ OpenAIClient(NonAzureOpenAIClientImpl serviceClient) { this.serviceClient = null; openAIServiceClient = serviceClient; }
Yes. More logging infor will be shown with this configured. It is for debugging purposes. I will remove it.
OpenAIClientBuilder getOpenAIClientBuilder(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { OpenAIClientBuilder builder = new OpenAIClientBuilder() .httpClient(httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (getTestMode() == TestMode.PLAYBACK) { builder .endpoint("https: .credential(new AzureKeyCredential(FAKE_API_KEY)); } else if (getTestMode() == TestMode.RECORD) { builder .addPolicy(interceptorManager.getRecordPolicy()) .endpoint(Configuration.getGlobalConfiguration().get("AZURE_OPENAI_ENDPOINT")) .credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_OPENAI_KEY"))); } else { builder .endpoint(Configuration.getGlobalConfiguration().get("AZURE_OPENAI_ENDPOINT")) .credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_OPENAI_KEY"))); } return builder; }
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
OpenAIClientBuilder getOpenAIClientBuilder(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { OpenAIClientBuilder builder = new OpenAIClientBuilder() .httpClient(httpClient) .serviceVersion(serviceVersion); if (getTestMode() == TestMode.PLAYBACK) { builder .endpoint("https: .credential(new AzureKeyCredential(FAKE_API_KEY)); } else if (getTestMode() == TestMode.RECORD) { builder .addPolicy(interceptorManager.getRecordPolicy()) .endpoint(Configuration.getGlobalConfiguration().get("AZURE_OPENAI_ENDPOINT")) .credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_OPENAI_KEY"))); } else { builder .endpoint(Configuration.getGlobalConfiguration().get("AZURE_OPENAI_ENDPOINT")) .credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_OPENAI_KEY"))); } return builder; }
class OpenAIClientTestBase extends TestProxyTestBase { OpenAIClientBuilder getNonAzureOpenAIClientBuilder(HttpClient httpClient) { OpenAIClientBuilder builder = new OpenAIClientBuilder() .httpClient(httpClient); if (getTestMode() == TestMode.PLAYBACK) { builder .credential(new NonAzureOpenAIKeyCredential(FAKE_API_KEY)); } else if (getTestMode() == TestMode.RECORD) { builder .addPolicy(interceptorManager.getRecordPolicy()) .credential(new NonAzureOpenAIKeyCredential(Configuration.getGlobalConfiguration().get("NON_AZURE_OPENAI_KEY"))); } else { builder .credential(new NonAzureOpenAIKeyCredential(Configuration.getGlobalConfiguration().get("NON_AZURE_OPENAI_KEY"))); } return builder; } @Test public abstract void testGetCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetChatCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetChatCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetEmbeddings(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetEmbeddingsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion); void getCompletionsRunner(BiConsumer<String, List<String>> testRunner) { String deploymentId = "text-davinci-003"; List<String> prompt = new ArrayList<>(); prompt.add("Say this is a test"); testRunner.accept(deploymentId, prompt); } void getCompletionsFromSinglePromptRunner(BiConsumer<String, String> testRunner) { String deploymentId = "text-davinci-003"; String prompt = "Say this is a test"; testRunner.accept(deploymentId, prompt); } void getChatCompletionsRunner(BiConsumer<String, List<ChatMessage>> testRunner) { testRunner.accept("gpt-35-turbo", getChatMessages()); } void getChatCompletionsForNonAzureRunner(BiConsumer<String, List<ChatMessage>> testRunner) { testRunner.accept("gpt-3.5-turbo", getChatMessages()); } void getEmbeddingRunner(BiConsumer<String, EmbeddingsOptions> testRunner) { testRunner.accept("text-embedding-ada-002", new EmbeddingsOptions(Arrays.asList("Your text string goes here"))); } void getEmbeddingNonAzureRunner(BiConsumer<String, EmbeddingsOptions> testRunner) { testRunner.accept("text-embedding-ada-002", new EmbeddingsOptions(Arrays.asList("Your text string goes here"))); } void getImageGenerationRunner(Consumer<ImageGenerationOptions> testRunner) { testRunner.accept( new ImageGenerationOptions("A drawing of the Seattle skyline in the style of Van Gogh") ); } void getChatFunctionForNonAzureRunner(BiConsumer<String, ChatCompletionsOptions> testRunner) { testRunner.accept("gpt-3.5-turbo-0613", getChatMessagesWithFunction()); } void getChatFunctionForRunner(BiConsumer<String, ChatCompletionsOptions> testRunner) { testRunner.accept("gpt-4", getChatMessagesWithFunction()); } private List<ChatMessage> getChatMessages() { List<ChatMessage> chatMessages = new ArrayList<>(); chatMessages.add(new ChatMessage(ChatRole.SYSTEM).setContent("You are a helpful assistant. You will talk like a pirate.")); chatMessages.add(new ChatMessage(ChatRole.USER).setContent("Can you help me?")); chatMessages.add(new ChatMessage(ChatRole.ASSISTANT).setContent("Of course, me hearty! What can I do for ye?")); chatMessages.add(new ChatMessage(ChatRole.USER).setContent("What's the best way to train a parrot?")); return chatMessages; } private ChatCompletionsOptions getChatMessagesWithFunction() { FunctionDefinition functionDefinition = new FunctionDefinition("MyFunction"); Parameters parameters = new Parameters(); functionDefinition.setParameters(parameters); List<FunctionDefinition> functions = Arrays.asList(functionDefinition); List<ChatMessage> chatMessages = new ArrayList<>(); chatMessages.add(new ChatMessage(ChatRole.USER).setContent("What's the weather like in San Francisco in Celsius?")); ChatCompletionsOptions chatCompletionOptions = new ChatCompletionsOptions(chatMessages); chatCompletionOptions.setFunctions(functions); return chatCompletionOptions; } static void assertCompletions(int choicesPerPrompt, Completions actual) { assertCompletions(choicesPerPrompt, "stop", actual); } static void assertCompletions(int choicesPerPrompt, String expectedFinishReason, Completions actual) { assertNotNull(actual); assertInstanceOf(Completions.class, actual); assertChoices(choicesPerPrompt, expectedFinishReason, actual.getChoices()); assertNotNull(actual.getUsage()); } static <T> T assertAndGetValueFromResponse(Response<BinaryData> actualResponse, Class<T> clazz, int expectedCode) { assertNotNull(actualResponse); assertEquals(expectedCode, actualResponse.getStatusCode()); assertInstanceOf(Response.class, actualResponse); BinaryData binaryData = actualResponse.getValue(); assertNotNull(binaryData); T object = binaryData.toObject(clazz); assertNotNull(object); assertInstanceOf(clazz, object); return object; } static void assertChoices(int choicesPerPrompt, String expectedFinishReason, List<Choice> actual) { assertEquals(choicesPerPrompt, actual.size()); for (int i = 0; i < actual.size(); i++) { assertChoice(i, expectedFinishReason, actual.get(i)); } } static void assertChoice(int index, String expectedFinishReason, Choice actual) { assertNotNull(actual.getText()); assertEquals(index, actual.getIndex()); assertEquals(expectedFinishReason, actual.getFinishReason().toString()); } static void assertChatCompletions(int choiceCount, ChatCompletions actual) { List<ChatChoice> choices = actual.getChoices(); assertNotNull(choices); assertTrue(choices.size() > 0); assertChatChoices(choiceCount, "stop", ChatRole.ASSISTANT, choices); assertNotNull(actual.getUsage()); } static void assertChatCompletionsStream(ChatCompletions chatCompletions) { if (chatCompletions.getId() != null && !chatCompletions.getId().isEmpty()) { assertNotNull(chatCompletions.getId()); assertNotNull(chatCompletions.getChoices()); assertFalse(chatCompletions.getChoices().isEmpty()); assertNotNull(chatCompletions.getChoices().get(0).getDelta()); } } static void assertCompletionsStream(Completions completions) { if (completions.getId() != null && !completions.getId().isEmpty()) { assertNotNull(completions.getId()); assertNotNull(completions.getChoices()); assertFalse(completions.getChoices().isEmpty()); assertNotNull(completions.getChoices().get(0).getText()); } } static void assertChatCompletions(int choiceCount, String expectedFinishReason, ChatRole chatRole, ChatCompletions actual) { List<ChatChoice> choices = actual.getChoices(); assertNotNull(choices); assertTrue(choices.size() > 0); assertChatChoices(choiceCount, expectedFinishReason, chatRole, choices); assertNotNull(actual.getUsage()); } static void assertChatChoices(int choiceCount, String expectedFinishReason, ChatRole chatRole, List<ChatChoice> actual) { assertEquals(choiceCount, actual.size()); for (int i = 0; i < actual.size(); i++) { assertChatChoice(i, expectedFinishReason, chatRole, actual.get(i)); } } static void assertChatChoice(int index, String expectedFinishReason, ChatRole chatRole, ChatChoice actual) { assertEquals(index, actual.getIndex()); assertEquals(chatRole, actual.getMessage().getRole()); assertNotNull(actual.getMessage().getContent()); assertEquals(expectedFinishReason, actual.getFinishReason().toString()); } static void assertEmbeddings(Embeddings actual) { List<EmbeddingItem> data = actual.getData(); assertNotNull(data); assertTrue(data.size() > 0); for (EmbeddingItem item : data) { List<Double> embedding = item.getEmbedding(); assertNotNull(embedding); assertTrue(embedding.size() > 0); } assertNotNull(actual.getUsage()); } static void assertImageResponse(ImageResponse actual) { assertNotNull(actual.getData()); assertFalse(actual.getData().isEmpty()); } static <T> T assertFunctionCall(ChatChoice actual, String functionName, Class<T> myPropertiesClazz) { assertEquals(0, actual.getIndex()); assertEquals("function_call", actual.getFinishReason().toString()); FunctionCall functionCall = actual.getMessage().getFunctionCall(); assertEquals(functionName, functionCall.getName()); BinaryData argumentJson = BinaryData.fromString(functionCall.getArguments()); return argumentJson.toObject(myPropertiesClazz); } }
class OpenAIClientTestBase extends TestProxyTestBase { OpenAIClientBuilder getNonAzureOpenAIClientBuilder(HttpClient httpClient) { OpenAIClientBuilder builder = new OpenAIClientBuilder() .httpClient(httpClient); if (getTestMode() == TestMode.PLAYBACK) { builder .credential(new NonAzureOpenAIKeyCredential(FAKE_API_KEY)); } else if (getTestMode() == TestMode.RECORD) { builder .addPolicy(interceptorManager.getRecordPolicy()) .credential(new NonAzureOpenAIKeyCredential(Configuration.getGlobalConfiguration().get("NON_AZURE_OPENAI_KEY"))); } else { builder .credential(new NonAzureOpenAIKeyCredential(Configuration.getGlobalConfiguration().get("NON_AZURE_OPENAI_KEY"))); } return builder; } @Test public abstract void testGetCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetChatCompletions(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetChatCompletionsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetEmbeddings(HttpClient httpClient, OpenAIServiceVersion serviceVersion); @Test public abstract void testGetEmbeddingsWithResponse(HttpClient httpClient, OpenAIServiceVersion serviceVersion); void getCompletionsRunner(BiConsumer<String, List<String>> testRunner) { String deploymentId = "text-davinci-003"; List<String> prompt = new ArrayList<>(); prompt.add("Say this is a test"); testRunner.accept(deploymentId, prompt); } void getCompletionsFromSinglePromptRunner(BiConsumer<String, String> testRunner) { String deploymentId = "text-davinci-003"; String prompt = "Say this is a test"; testRunner.accept(deploymentId, prompt); } void getChatCompletionsRunner(BiConsumer<String, List<ChatMessage>> testRunner) { testRunner.accept("gpt-35-turbo", getChatMessages()); } void getChatCompletionsForNonAzureRunner(BiConsumer<String, List<ChatMessage>> testRunner) { testRunner.accept("gpt-3.5-turbo", getChatMessages()); } void getEmbeddingRunner(BiConsumer<String, EmbeddingsOptions> testRunner) { testRunner.accept("text-embedding-ada-002", new EmbeddingsOptions(Arrays.asList("Your text string goes here"))); } void getEmbeddingNonAzureRunner(BiConsumer<String, EmbeddingsOptions> testRunner) { testRunner.accept("text-embedding-ada-002", new EmbeddingsOptions(Arrays.asList("Your text string goes here"))); } void getImageGenerationRunner(Consumer<ImageGenerationOptions> testRunner) { testRunner.accept( new ImageGenerationOptions("A drawing of the Seattle skyline in the style of Van Gogh") ); } void getChatFunctionForNonAzureRunner(BiConsumer<String, ChatCompletionsOptions> testRunner) { testRunner.accept("gpt-3.5-turbo-0613", getChatMessagesWithFunction()); } void getChatFunctionForRunner(BiConsumer<String, ChatCompletionsOptions> testRunner) { testRunner.accept("gpt-4", getChatMessagesWithFunction()); } void getChatCompletionsContentFilterRunner(BiConsumer<String, List<ChatMessage>> testRunner) { testRunner.accept("gpt-4", getChatMessages()); } void getCompletionsContentFilterRunner(BiConsumer<String, String> testRunner) { testRunner.accept("gpt-35-turbo", "What is 3 times 4?"); } void getChatCompletionsContentFilterRunnerForNonAzure(BiConsumer<String, List<ChatMessage>> testRunner) { testRunner.accept("gpt-3.5-turbo-0613", getChatMessages()); } void getCompletionsContentFilterRunnerForNonAzure(BiConsumer<String, String> testRunner) { testRunner.accept("text-davinci-002", "What is 3 times 4?"); } private List<ChatMessage> getChatMessages() { List<ChatMessage> chatMessages = new ArrayList<>(); chatMessages.add(new ChatMessage(ChatRole.SYSTEM).setContent("You are a helpful assistant. You will talk like a pirate.")); chatMessages.add(new ChatMessage(ChatRole.USER).setContent("Can you help me?")); chatMessages.add(new ChatMessage(ChatRole.ASSISTANT).setContent("Of course, me hearty! What can I do for ye?")); chatMessages.add(new ChatMessage(ChatRole.USER).setContent("What's the best way to train a parrot?")); return chatMessages; } private ChatCompletionsOptions getChatMessagesWithFunction() { FunctionDefinition functionDefinition = new FunctionDefinition("MyFunction"); Parameters parameters = new Parameters(); functionDefinition.setParameters(parameters); List<FunctionDefinition> functions = Arrays.asList(functionDefinition); List<ChatMessage> chatMessages = new ArrayList<>(); chatMessages.add(new ChatMessage(ChatRole.USER).setContent("What's the weather like in San Francisco in Celsius?")); ChatCompletionsOptions chatCompletionOptions = new ChatCompletionsOptions(chatMessages); chatCompletionOptions.setFunctions(functions); return chatCompletionOptions; } static void assertCompletions(int choicesPerPrompt, Completions actual) { assertCompletions(choicesPerPrompt, "stop", actual); } static void assertCompletions(int choicesPerPrompt, String expectedFinishReason, Completions actual) { assertNotNull(actual); assertInstanceOf(Completions.class, actual); assertChoices(choicesPerPrompt, expectedFinishReason, actual.getChoices()); assertNotNull(actual.getUsage()); } static <T> T assertAndGetValueFromResponse(Response<BinaryData> actualResponse, Class<T> clazz, int expectedCode) { assertNotNull(actualResponse); assertEquals(expectedCode, actualResponse.getStatusCode()); assertInstanceOf(Response.class, actualResponse); BinaryData binaryData = actualResponse.getValue(); assertNotNull(binaryData); T object = binaryData.toObject(clazz); assertNotNull(object); assertInstanceOf(clazz, object); return object; } static void assertChoices(int choicesPerPrompt, String expectedFinishReason, List<Choice> actual) { assertEquals(choicesPerPrompt, actual.size()); for (int i = 0; i < actual.size(); i++) { assertChoice(i, expectedFinishReason, actual.get(i)); } } static void assertChoice(int index, String expectedFinishReason, Choice actual) { assertNotNull(actual.getText()); assertEquals(index, actual.getIndex()); assertEquals(expectedFinishReason, actual.getFinishReason().toString()); } static void assertChatCompletions(int choiceCount, ChatCompletions actual) { List<ChatChoice> choices = actual.getChoices(); assertNotNull(choices); assertTrue(choices.size() > 0); assertChatChoices(choiceCount, "stop", ChatRole.ASSISTANT, choices); assertNotNull(actual.getUsage()); } static void assertChatCompletionsStream(ChatCompletions chatCompletions) { if (chatCompletions.getId() != null && !chatCompletions.getId().isEmpty()) { assertNotNull(chatCompletions.getId()); assertNotNull(chatCompletions.getChoices()); assertFalse(chatCompletions.getChoices().isEmpty()); assertNotNull(chatCompletions.getChoices().get(0).getDelta()); } } static void assertCompletionsStream(Completions completions) { if (completions.getId() != null && !completions.getId().isEmpty()) { assertNotNull(completions.getId()); assertNotNull(completions.getChoices()); assertFalse(completions.getChoices().isEmpty()); assertNotNull(completions.getChoices().get(0).getText()); } } static void assertChatCompletions(int choiceCount, String expectedFinishReason, ChatRole chatRole, ChatCompletions actual) { List<ChatChoice> choices = actual.getChoices(); assertNotNull(choices); assertTrue(choices.size() > 0); assertChatChoices(choiceCount, expectedFinishReason, chatRole, choices); assertNotNull(actual.getUsage()); } static void assertChatChoices(int choiceCount, String expectedFinishReason, ChatRole chatRole, List<ChatChoice> actual) { assertEquals(choiceCount, actual.size()); for (int i = 0; i < actual.size(); i++) { assertChatChoice(i, expectedFinishReason, chatRole, actual.get(i)); } } static void assertChatChoice(int index, String expectedFinishReason, ChatRole chatRole, ChatChoice actual) { assertEquals(index, actual.getIndex()); assertEquals(chatRole, actual.getMessage().getRole()); assertNotNull(actual.getMessage().getContent()); assertEquals(expectedFinishReason, actual.getFinishReason().toString()); } static void assertEmbeddings(Embeddings actual) { List<EmbeddingItem> data = actual.getData(); assertNotNull(data); assertTrue(data.size() > 0); for (EmbeddingItem item : data) { List<Double> embedding = item.getEmbedding(); assertNotNull(embedding); assertTrue(embedding.size() > 0); } assertNotNull(actual.getUsage()); } static void assertImageResponse(ImageResponse actual) { assertNotNull(actual.getData()); assertFalse(actual.getData().isEmpty()); } static <T> T assertFunctionCall(ChatChoice actual, String functionName, Class<T> myPropertiesClazz) { assertEquals(0, actual.getIndex()); assertEquals("function_call", actual.getFinishReason().toString()); FunctionCall functionCall = actual.getMessage().getFunctionCall(); assertEquals(functionName, functionCall.getName()); BinaryData argumentJson = BinaryData.fromString(functionCall.getArguments()); return argumentJson.toObject(myPropertiesClazz); } static void assertSafeContentFilterResults(ContentFilterResults contentFilterResults) { assertNotNull(contentFilterResults); assertFalse(contentFilterResults.getHate().isFiltered()); assertEquals(contentFilterResults.getHate().getSeverity(), ContentFilterSeverity.SAFE); assertFalse(contentFilterResults.getSexual().isFiltered()); assertEquals(contentFilterResults.getSexual().getSeverity(), ContentFilterSeverity.SAFE); assertFalse(contentFilterResults.getSelfHarm().isFiltered()); assertEquals(contentFilterResults.getSelfHarm().getSeverity(), ContentFilterSeverity.SAFE); assertFalse(contentFilterResults.getViolence().isFiltered()); assertEquals(contentFilterResults.getViolence().getSeverity(), ContentFilterSeverity.SAFE); } }
```suggestion ```
private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .skipRequest((ignored1, ignored2) -> false) .assertAsync() .build(); }
.skipRequest((ignored1, ignored2) -> false)
private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertAsync() .build(); }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<RemoveParticipantsResult> removeParticipantResponse = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listRoomTestFirstRoomIsValidSuccess"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<CommunicationRoom> listRoomResponse = roomsAsyncClient.listRooms(); StepVerifier.create(listRoomResponse.take(1)) .assertNext(room -> { assertEquals(true, room.getRoomId() != null); assertEquals(true, room.getCreatedAt() != null); assertEquals(true, room.getValidFrom() != null); assertEquals(true, room.getValidUntil() != null); }) .expectComplete() .verify(); Mono<Response<Void>> deleteResponse = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(deleteResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString( buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), RoomsServiceVersion.V2023_06_14); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<RemoveParticipantsResult> removeParticipantResponse = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listRoomTestFirstRoomIsValidSuccess"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<CommunicationRoom> listRoomResponse = roomsAsyncClient.listRooms(); StepVerifier.create(listRoomResponse.take(1)) .assertNext(room -> { assertEquals(true, room.getRoomId() != null); assertEquals(true, room.getCreatedAt() != null); assertEquals(true, room.getValidFrom() != null); assertEquals(true, room.getValidUntil() != null); }) .expectComplete() .verify(); Mono<Response<Void>> deleteResponse = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(deleteResponse) .assertNext(result -> { assertEquals(result.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString( buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), RoomsServiceVersion.V2023_06_14); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
```suggestion ```
private HttpClient buildSyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .skipRequest((ignored1, ignored2) -> false) .assertSync() .build(); }
.skipRequest((ignored1, ignored2) -> false)
private HttpClient buildSyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .assertSync() .build(); }
class RoomsClientTest extends RoomsTestBase { private RoomsClient roomsClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncWithFullOperation(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncWithFullOperation"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createCommunicationRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createCommunicationRoom); String roomId = createCommunicationRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(4)); CommunicationRoom updateCommunicationRoom = roomsClient.updateRoom(roomId, updateRoomOptions); assertEquals(true, updateCommunicationRoom.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); assertHappyPath(updateCommunicationRoom); CommunicationRoom getCommunicationRoom = roomsClient.getRoom(roomId); assertHappyPath(getCommunicationRoom); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomSync(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "deleteRoomSync"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createCommunicationRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createCommunicationRoom); String roomId = createCommunicationRoom.getRoomId(); roomsClient.deleteRoom(roomId); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncWithFullOperationWithResponse(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncWithFullOperationWithResponse"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Response<CommunicationRoom> createdRoomResponse = roomsClient.createRoomWithResponse(createRoomOptions, Context.NONE); assertHappyPath(createdRoomResponse, 201); String roomId = createdRoomResponse.getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(4)); Response<CommunicationRoom> updateRoomResponse = roomsClient.updateRoomWithResponse(roomId, updateRoomOptions, Context.NONE); assertHappyPath(updateRoomResponse, 200); Response<CommunicationRoom> getRoomResponse = roomsClient.getRoomWithResponse(roomId, Context.NONE); assertHappyPath(getRoomResponse, 200); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createCommunicationRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createCommunicationRoom); String roomId = createCommunicationRoom.getRoomId(); PagedIterable<CommunicationRoom> listRoomResponse = roomsClient.listRooms(); List<CommunicationRoom> rooms = listRoomResponse.stream().collect(Collectors.toList()); assertHappyPath(rooms.get(0)); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsSyncWithFullFlow(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsSyncWithFullFlow"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createCommunicationRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createCommunicationRoom); String roomId = createCommunicationRoom.getRoomId(); PagedIterable<RoomParticipant> listParticipantsResponse1 = roomsClient.listParticipants(roomId); assertEquals(0, listParticipantsResponse1.stream().count()); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addPartcipantResponse = roomsClient.addOrUpdateParticipants(roomId, participants); assertEquals(true, addPartcipantResponse instanceof AddOrUpdateParticipantsResult); PagedIterable<RoomParticipant> listParticipantsResponse2 = roomsClient.listParticipants(roomId); assertEquals(3, listParticipantsResponse2.stream().count()); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); AddOrUpdateParticipantsResult updateParticipantResponse = roomsClient.addOrUpdateParticipants(roomId, participantsToUpdate); assertEquals(true, updateParticipantResponse instanceof AddOrUpdateParticipantsResult); PagedIterable<RoomParticipant> listParticipantsResponse3 = roomsClient.listParticipants(roomId); for (RoomParticipant participant : listParticipantsResponse3) { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); } List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); RemoveParticipantsResult removeParticipantResponse = roomsClient.removeParticipants(roomId, participantsIdentifiersForParticipants); PagedIterable<RoomParticipant> listParticipantsResponse4 = roomsClient.listParticipants(roomId); assertEquals(1, listParticipantsResponse4.stream().count()); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleSyncWithFullOperationWithResponse(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateParticipantsToDefaultRoleSyncWithFullOperationWithResponse"); assertNotNull(roomsClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Response<CommunicationRoom> createCommunicationRoom = roomsClient.createRoomWithResponse(createRoomOptions, Context.NONE); assertHappyPath(createCommunicationRoom, 201); String roomId = createCommunicationRoom.getValue().getRoomId(); RoomParticipant firstParticipantToUpdate = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(null); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantToUpdate); Response<AddOrUpdateParticipantsResult> addPartcipantResponse = roomsClient .addOrUpdateParticipantsWithResponse(roomId, participantsToUpdate, Context.NONE); assertEquals(200, addPartcipantResponse.getStatusCode()); PagedIterable<RoomParticipant> listResponse = roomsClient.listParticipants(roomId); for (RoomParticipant participant : listResponse) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsSyncWithFullOperation(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateParticipantsSyncWithFullOperation"); assertNotNull(roomsClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.ATTENDEE); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); CommunicationRoom createCommunicationRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createCommunicationRoom); String roomId = createCommunicationRoom.getRoomId(); RoomParticipant firstParticipantToUpdate = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipantToUpdate = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantToUpdate, secondParticipantToUpdate); AddOrUpdateParticipantsResult addPartcipantResponse = roomsClient.addOrUpdateParticipants(roomId, participantsToUpdate); PagedIterable<RoomParticipant> listResponse = roomsClient.listParticipants(roomId); for (RoomParticipant participant : listResponse) { assertEquals(ParticipantRole.PRESENTER, participant.getRole()); } Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void patchMeetingValidTimeWithResponse(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "patchMeetingValidTimeWithResponse"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM); Response<CommunicationRoom> createdRoomResponse = roomsClient.createRoomWithResponse(createRoomOptions, Context.NONE); assertHappyPath(createdRoomResponse, 201); String roomId = createdRoomResponse.getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Response<CommunicationRoom> updateRoomResponse = roomsClient.updateRoomWithResponse(roomId, updateRoomOptions, Context.NONE); assertHappyPath(updateRoomResponse, 200); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomIdReturnBadRequest(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "getRoomWithUnexistingRoomIdReturnBadRequest"); assertNotNull(roomsClient); assertThrows(HttpResponseException.class, () -> { roomsClient.getRoom(nonExistRoomId); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithUnexistingRoomIdReturnBadRequest(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "deleteRoomWithUnexistingRoomIdReturnBadRequest"); assertNotNull(roomsClient); assertThrows(HttpResponseException.class, () -> { roomsClient.deleteRoomWithResponse(nonExistRoomId, Context.NONE); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncNoAttributes(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncNoAttributes"); assertNotNull(roomsClient); CommunicationRoom createCommunicationRoom = roomsClient.createRoom(new CreateRoomOptions()); assertHappyPath(createCommunicationRoom); String roomId = createCommunicationRoom.getRoomId(); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncOnlyValidFrom(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncOnlyValidFrom"); assertNotNull(roomsClient); CommunicationRoom createCommunicationRoom = roomsClient .createRoom(new CreateRoomOptions().setValidFrom(VALID_FROM)); assertHappyPath(createCommunicationRoom); String roomId = createCommunicationRoom.getRoomId(); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncOnlyValidUntil(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncOnlyValidUntil"); assertNotNull(roomsClient); CommunicationRoom createCommunicationRoom = roomsClient .createRoom(new CreateRoomOptions().setValidUntil(VALID_UNTIL)); assertHappyPath(createCommunicationRoom); String roomId = createCommunicationRoom.getRoomId(); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncOnlyValidUntilGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncOnlyValidUntilGreaterThan180"); assertNotNull(roomsClient); assertThrows(HttpResponseException.class, () -> { roomsClient.createRoom(new CreateRoomOptions().setValidUntil(VALID_FROM.plusDays(181))); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncOnlyValidFromGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncOnlyValidFromGreaterThan180"); assertNotNull(roomsClient); assertThrows(HttpResponseException.class, () -> { roomsClient.createRoom(new CreateRoomOptions().setValidFrom(VALID_FROM.plusDays(181))); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncValidFromValidUntilGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncValidFromValidUntilGreaterThan180"); assertNotNull(roomsClient); assertThrows(HttpResponseException.class, () -> { roomsClient.createRoom( new CreateRoomOptions().setValidFrom(VALID_FROM).setValidUntil(VALID_FROM.plusDays(181))); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncBadParticipantMri(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncBadParticipantMri"); assertNotNull(roomsClient); List<RoomParticipant> badParticipant = Arrays .asList(new RoomParticipant(new CommunicationUserIdentifier("badMRI"))); assertThrows(HttpResponseException.class, () -> { roomsClient.createRoom(new CreateRoomOptions().setParticipants(badParticipant)); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomSyncOnlyValidFrom(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateRoomSyncOnlyValidFrom"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createdRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createdRoom); String roomId = createdRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusMonths(4)); assertThrows(HttpResponseException.class, () -> { roomsClient.updateRoom(roomId, updateRoomOptions); }); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomSyncOnlyValidUntil(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateRoomSyncOnlyValidUntil"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createdRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createdRoom); String roomId = createdRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidUntil(VALID_FROM.plusMonths(4)); assertThrows(HttpResponseException.class, () -> { roomsClient.updateRoom(roomId, updateRoomOptions); }); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomSyncValidUntilGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateRoomSyncValidUntilGreaterThan180"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createdRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createdRoom); String roomId = createdRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); assertThrows(HttpResponseException.class, () -> { roomsClient.updateRoom(roomId, updateRoomOptions); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomSyncValidFromGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateRoomSyncValidFromGreaterThan180"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createdRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createdRoom); String roomId = createdRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(VALID_UNTIL); assertThrows(HttpResponseException.class, () -> { roomsClient.updateRoom(roomId, updateRoomOptions); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncWithResponseNoAttributes(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncWithResponseNoAttributes"); assertNotNull(roomsClient); Response<CommunicationRoom> createCommunicationRoom = roomsClient .createRoomWithResponse(new CreateRoomOptions(), Context.NONE); assertHappyPath(createCommunicationRoom, 201); String roomId = createCommunicationRoom.getValue().getRoomId(); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncWithResponseOnlyValidFrom(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncWithResponseOnlyValidFrom"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM); Response<CommunicationRoom> createCommunicationRoom = roomsClient.createRoomWithResponse(createRoomOptions, Context.NONE); assertHappyPath(createCommunicationRoom, 201); String roomId = createCommunicationRoom.getValue().getRoomId(); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncWithResponseOnlyValidUntil(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncWithResponseOnlyValidUntil"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidUntil(VALID_UNTIL); Response<CommunicationRoom> createCommunicationRoom = roomsClient.createRoomWithResponse(createRoomOptions, Context.NONE); assertHappyPath(createCommunicationRoom, 201); String roomId = createCommunicationRoom.getValue().getRoomId(); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncWithResponseOnlyValidUntilGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncWithResponseOnlyValidUntilGreaterThan180"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(null) .setValidUntil(VALID_FROM.plusDays(181)) .setParticipants(null); assertThrows(HttpResponseException.class, () -> { roomsClient.createRoomWithResponse(createRoomOptions, Context.NONE); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncWithResponseOnlyValidFromGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncWithResponseOnlyValidFromGreaterThan180"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(null) .setParticipants(null); assertThrows(HttpResponseException.class, () -> { roomsClient.createRoomWithResponse(createRoomOptions, Context.NONE); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncWithResponseValidFromValidUntilGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncWithResponseValidFromValidUntilGreaterThan180"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); assertThrows(HttpResponseException.class, () -> { roomsClient.createRoomWithResponse(createRoomOptions, Context.NONE); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomSyncWithResponseOnlyValidFrom(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateRoomSyncWithResponseOnlyValidFrom"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createdRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createdRoom); String roomId = createdRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusMonths(4)) .setValidUntil(null); assertThrows(HttpResponseException.class, () -> { roomsClient.updateRoomWithResponse(roomId, updateRoomOptions, Context.NONE); }); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomSyncWithResponseOnlyValidUntil(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateRoomSyncWithResponseOnlyValidUntil"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createdRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createdRoom); String roomId = createdRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(null) .setValidUntil(VALID_FROM.plusMonths(4)); assertThrows(HttpResponseException.class, () -> { roomsClient.updateRoomWithResponse(roomId, updateRoomOptions, Context.NONE); }); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomSyncWithResponseValidUntilGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateRoomSyncValidUntilWithResponseGreaterThan180"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createdRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createdRoom); String roomId = createdRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); assertThrows(HttpResponseException.class, () -> { roomsClient.updateRoomWithResponse(roomId, updateRoomOptions, Context.NONE); }); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomSyncWithResponseValidFromGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateRoomSyncWithResponseValidFromGreaterThan180"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createdRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createdRoom); String roomId = createdRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(VALID_UNTIL); assertThrows(HttpResponseException.class, () -> { roomsClient.updateRoomWithResponse(roomId, updateRoomOptions, Context.NONE); }); } private RoomsClient setupSyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString( buildSyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), RoomsServiceVersion.V2023_06_14); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildClient(); } }
class RoomsClientTest extends RoomsTestBase { private RoomsClient roomsClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncWithFullOperation(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncWithFullOperation"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createCommunicationRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createCommunicationRoom); String roomId = createCommunicationRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(4)); CommunicationRoom updateCommunicationRoom = roomsClient.updateRoom(roomId, updateRoomOptions); assertEquals(true, updateCommunicationRoom.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); assertHappyPath(updateCommunicationRoom); CommunicationRoom getCommunicationRoom = roomsClient.getRoom(roomId); assertHappyPath(getCommunicationRoom); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomSync(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "deleteRoomSync"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createCommunicationRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createCommunicationRoom); String roomId = createCommunicationRoom.getRoomId(); roomsClient.deleteRoom(roomId); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncWithFullOperationWithResponse(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncWithFullOperationWithResponse"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Response<CommunicationRoom> createdRoomResponse = roomsClient.createRoomWithResponse(createRoomOptions, Context.NONE); assertHappyPath(createdRoomResponse, 201); String roomId = createdRoomResponse.getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(4)); Response<CommunicationRoom> updateRoomResponse = roomsClient.updateRoomWithResponse(roomId, updateRoomOptions, Context.NONE); assertHappyPath(updateRoomResponse, 200); Response<CommunicationRoom> getRoomResponse = roomsClient.getRoomWithResponse(roomId, Context.NONE); assertHappyPath(getRoomResponse, 200); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createCommunicationRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createCommunicationRoom); String roomId = createCommunicationRoom.getRoomId(); PagedIterable<CommunicationRoom> listRoomResponse = roomsClient.listRooms(); List<CommunicationRoom> rooms = listRoomResponse.stream().collect(Collectors.toList()); assertHappyPath(rooms.get(0)); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsSyncWithFullFlow(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsSyncWithFullFlow"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createCommunicationRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createCommunicationRoom); String roomId = createCommunicationRoom.getRoomId(); PagedIterable<RoomParticipant> listParticipantsResponse1 = roomsClient.listParticipants(roomId); assertEquals(0, listParticipantsResponse1.stream().count()); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addPartcipantResponse = roomsClient.addOrUpdateParticipants(roomId, participants); assertEquals(true, addPartcipantResponse instanceof AddOrUpdateParticipantsResult); PagedIterable<RoomParticipant> listParticipantsResponse2 = roomsClient.listParticipants(roomId); assertEquals(3, listParticipantsResponse2.stream().count()); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); AddOrUpdateParticipantsResult updateParticipantResponse = roomsClient.addOrUpdateParticipants(roomId, participantsToUpdate); assertEquals(true, updateParticipantResponse instanceof AddOrUpdateParticipantsResult); PagedIterable<RoomParticipant> listParticipantsResponse3 = roomsClient.listParticipants(roomId); for (RoomParticipant participant : listParticipantsResponse3) { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); } List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); RemoveParticipantsResult removeParticipantResponse = roomsClient.removeParticipants(roomId, participantsIdentifiersForParticipants); PagedIterable<RoomParticipant> listParticipantsResponse4 = roomsClient.listParticipants(roomId); assertEquals(1, listParticipantsResponse4.stream().count()); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleSyncWithFullOperationWithResponse(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateParticipantsToDefaultRoleSyncWithFullOperationWithResponse"); assertNotNull(roomsClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Response<CommunicationRoom> createCommunicationRoom = roomsClient.createRoomWithResponse(createRoomOptions, Context.NONE); assertHappyPath(createCommunicationRoom, 201); String roomId = createCommunicationRoom.getValue().getRoomId(); RoomParticipant firstParticipantToUpdate = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(null); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantToUpdate); Response<AddOrUpdateParticipantsResult> addPartcipantResponse = roomsClient .addOrUpdateParticipantsWithResponse(roomId, participantsToUpdate, Context.NONE); assertEquals(200, addPartcipantResponse.getStatusCode()); PagedIterable<RoomParticipant> listResponse = roomsClient.listParticipants(roomId); for (RoomParticipant participant : listResponse) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsSyncWithFullOperation(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateParticipantsSyncWithFullOperation"); assertNotNull(roomsClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.ATTENDEE); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); CommunicationRoom createCommunicationRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createCommunicationRoom); String roomId = createCommunicationRoom.getRoomId(); RoomParticipant firstParticipantToUpdate = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipantToUpdate = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantToUpdate, secondParticipantToUpdate); AddOrUpdateParticipantsResult addPartcipantResponse = roomsClient.addOrUpdateParticipants(roomId, participantsToUpdate); PagedIterable<RoomParticipant> listResponse = roomsClient.listParticipants(roomId); for (RoomParticipant participant : listResponse) { assertEquals(ParticipantRole.PRESENTER, participant.getRole()); } Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void patchMeetingValidTimeWithResponse(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "patchMeetingValidTimeWithResponse"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM); Response<CommunicationRoom> createdRoomResponse = roomsClient.createRoomWithResponse(createRoomOptions, Context.NONE); assertHappyPath(createdRoomResponse, 201); String roomId = createdRoomResponse.getValue().getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Response<CommunicationRoom> updateRoomResponse = roomsClient.updateRoomWithResponse(roomId, updateRoomOptions, Context.NONE); assertHappyPath(updateRoomResponse, 200); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomIdReturnBadRequest(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "getRoomWithUnexistingRoomIdReturnBadRequest"); assertNotNull(roomsClient); assertThrows(HttpResponseException.class, () -> { roomsClient.getRoom(nonExistRoomId); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithUnexistingRoomIdReturnBadRequest(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "deleteRoomWithUnexistingRoomIdReturnBadRequest"); assertNotNull(roomsClient); assertThrows(HttpResponseException.class, () -> { roomsClient.deleteRoomWithResponse(nonExistRoomId, Context.NONE); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncNoAttributes(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncNoAttributes"); assertNotNull(roomsClient); CommunicationRoom createCommunicationRoom = roomsClient.createRoom(new CreateRoomOptions()); assertHappyPath(createCommunicationRoom); String roomId = createCommunicationRoom.getRoomId(); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncOnlyValidFrom(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncOnlyValidFrom"); assertNotNull(roomsClient); CommunicationRoom createCommunicationRoom = roomsClient .createRoom(new CreateRoomOptions().setValidFrom(VALID_FROM)); assertHappyPath(createCommunicationRoom); String roomId = createCommunicationRoom.getRoomId(); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncOnlyValidUntil(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncOnlyValidUntil"); assertNotNull(roomsClient); CommunicationRoom createCommunicationRoom = roomsClient .createRoom(new CreateRoomOptions().setValidUntil(VALID_UNTIL)); assertHappyPath(createCommunicationRoom); String roomId = createCommunicationRoom.getRoomId(); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncOnlyValidUntilGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncOnlyValidUntilGreaterThan180"); assertNotNull(roomsClient); assertThrows(HttpResponseException.class, () -> { roomsClient.createRoom(new CreateRoomOptions().setValidUntil(VALID_FROM.plusDays(181))); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncOnlyValidFromGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncOnlyValidFromGreaterThan180"); assertNotNull(roomsClient); assertThrows(HttpResponseException.class, () -> { roomsClient.createRoom(new CreateRoomOptions().setValidFrom(VALID_FROM.plusDays(181))); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncValidFromValidUntilGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncValidFromValidUntilGreaterThan180"); assertNotNull(roomsClient); assertThrows(HttpResponseException.class, () -> { roomsClient.createRoom( new CreateRoomOptions().setValidFrom(VALID_FROM).setValidUntil(VALID_FROM.plusDays(181))); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncBadParticipantMri(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncBadParticipantMri"); assertNotNull(roomsClient); List<RoomParticipant> badParticipant = Arrays .asList(new RoomParticipant(new CommunicationUserIdentifier("badMRI"))); assertThrows(HttpResponseException.class, () -> { roomsClient.createRoom(new CreateRoomOptions().setParticipants(badParticipant)); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomSyncOnlyValidFrom(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateRoomSyncOnlyValidFrom"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createdRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createdRoom); String roomId = createdRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusMonths(4)); assertThrows(HttpResponseException.class, () -> { roomsClient.updateRoom(roomId, updateRoomOptions); }); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomSyncOnlyValidUntil(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateRoomSyncOnlyValidUntil"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createdRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createdRoom); String roomId = createdRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidUntil(VALID_FROM.plusMonths(4)); assertThrows(HttpResponseException.class, () -> { roomsClient.updateRoom(roomId, updateRoomOptions); }); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomSyncValidUntilGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateRoomSyncValidUntilGreaterThan180"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createdRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createdRoom); String roomId = createdRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); assertThrows(HttpResponseException.class, () -> { roomsClient.updateRoom(roomId, updateRoomOptions); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomSyncValidFromGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateRoomSyncValidFromGreaterThan180"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createdRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createdRoom); String roomId = createdRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(VALID_UNTIL); assertThrows(HttpResponseException.class, () -> { roomsClient.updateRoom(roomId, updateRoomOptions); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncWithResponseNoAttributes(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncWithResponseNoAttributes"); assertNotNull(roomsClient); Response<CommunicationRoom> createCommunicationRoom = roomsClient .createRoomWithResponse(new CreateRoomOptions(), Context.NONE); assertHappyPath(createCommunicationRoom, 201); String roomId = createCommunicationRoom.getValue().getRoomId(); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncWithResponseOnlyValidFrom(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncWithResponseOnlyValidFrom"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM); Response<CommunicationRoom> createCommunicationRoom = roomsClient.createRoomWithResponse(createRoomOptions, Context.NONE); assertHappyPath(createCommunicationRoom, 201); String roomId = createCommunicationRoom.getValue().getRoomId(); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncWithResponseOnlyValidUntil(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncWithResponseOnlyValidUntil"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidUntil(VALID_UNTIL); Response<CommunicationRoom> createCommunicationRoom = roomsClient.createRoomWithResponse(createRoomOptions, Context.NONE); assertHappyPath(createCommunicationRoom, 201); String roomId = createCommunicationRoom.getValue().getRoomId(); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncWithResponseOnlyValidUntilGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncWithResponseOnlyValidUntilGreaterThan180"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(null) .setValidUntil(VALID_FROM.plusDays(181)) .setParticipants(null); assertThrows(HttpResponseException.class, () -> { roomsClient.createRoomWithResponse(createRoomOptions, Context.NONE); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncWithResponseOnlyValidFromGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncWithResponseOnlyValidFromGreaterThan180"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(null) .setParticipants(null); assertThrows(HttpResponseException.class, () -> { roomsClient.createRoomWithResponse(createRoomOptions, Context.NONE); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomSyncWithResponseValidFromValidUntilGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "createRoomSyncWithResponseValidFromValidUntilGreaterThan180"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); assertThrows(HttpResponseException.class, () -> { roomsClient.createRoomWithResponse(createRoomOptions, Context.NONE); }); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomSyncWithResponseOnlyValidFrom(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateRoomSyncWithResponseOnlyValidFrom"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createdRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createdRoom); String roomId = createdRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusMonths(4)) .setValidUntil(null); assertThrows(HttpResponseException.class, () -> { roomsClient.updateRoomWithResponse(roomId, updateRoomOptions, Context.NONE); }); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomSyncWithResponseOnlyValidUntil(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateRoomSyncWithResponseOnlyValidUntil"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createdRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createdRoom); String roomId = createdRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(null) .setValidUntil(VALID_FROM.plusMonths(4)); assertThrows(HttpResponseException.class, () -> { roomsClient.updateRoomWithResponse(roomId, updateRoomOptions, Context.NONE); }); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomSyncWithResponseValidUntilGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateRoomSyncValidUntilWithResponseGreaterThan180"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createdRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createdRoom); String roomId = createdRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusDays(181)); assertThrows(HttpResponseException.class, () -> { roomsClient.updateRoomWithResponse(roomId, updateRoomOptions, Context.NONE); }); Response<Void> deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE); assertEquals(deleteResponse.getStatusCode(), 204); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateRoomSyncWithResponseValidFromGreaterThan180(HttpClient httpClient) { roomsClient = setupSyncClient(httpClient, "updateRoomSyncWithResponseValidFromGreaterThan180"); assertNotNull(roomsClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); CommunicationRoom createdRoom = roomsClient.createRoom(createRoomOptions); assertHappyPath(createdRoom); String roomId = createdRoom.getRoomId(); UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM.plusDays(181)) .setValidUntil(VALID_UNTIL); assertThrows(HttpResponseException.class, () -> { roomsClient.updateRoomWithResponse(roomId, updateRoomOptions, Context.NONE); }); } private RoomsClient setupSyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString( buildSyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), RoomsServiceVersion.V2023_06_14); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildClient(); } }
Non-blocking - could we have a test to reverify if this doesn't introduce regressions on `crts` which doesn't end with 0?
public void testReplaceChangeFeedProcessorItemDeSerializer() throws JsonProcessingException { String json = "{\"current\":{\"id\":\"1946c04a-070b-48c0-8e36-517c8d2f92ed\",\"mypk\":\"mypk-1\",\"prop\":\"Gates\",\"_rid\":\"NopBALG34lcBAAAAAAAAAA==\",\"_self\":\"dbs/NopBAA==/colls/NopBALG34lc=/docs/NopBALG34lcBAAAAAAAAAA==/\",\"_etag\":\"\\\"00000000-0000-0000-b857-fda256f201d9\\\"\",\"_attachments\":\"attachments/\",\"_ts\":1689561604},\"metadata\":{\"lsn\":178,\"crts\":1689561600,\"operationType\":\"replace\",\"previousImageLSN\":176}}"; ChangeFeedProcessorItem changeFeedProcessorItem = simpleObjectMapper.readValue(json, ChangeFeedProcessorItem.class); JsonNode jsonNode = changeFeedProcessorItem.toJsonNode(); Assertions.assertThat(jsonNode.get("metadata").get("crts").asText()).isEqualTo("1689561600"); }
}
public void testReplaceChangeFeedProcessorItemDeSerializer() throws JsonProcessingException { String json = "{\"current\":{\"id\":\"1946c04a-070b-48c0-8e36-517c8d2f92ed\",\"mypk\":\"mypk-1\",\"prop\":\"Gates\",\"_rid\":\"NopBALG34lcBAAAAAAAAAA==\",\"_self\":\"dbs/NopBAA==/colls/NopBALG34lc=/docs/NopBALG34lcBAAAAAAAAAA==/\",\"_etag\":\"\\\"00000000-0000-0000-b857-fda256f201d9\\\"\",\"_attachments\":\"attachments/\",\"_ts\":1689561604},\"metadata\":{\"lsn\":178,\"crts\":1689561600,\"operationType\":\"replace\",\"previousImageLSN\":176,\"timeToLiveExpired\": true}}"; ChangeFeedProcessorItem changeFeedProcessorItem = simpleObjectMapper.readValue(json, ChangeFeedProcessorItem.class); JsonNode jsonNode = changeFeedProcessorItem.toJsonNode(); Assertions.assertThat(jsonNode.get("metadata").get("crts").asText()).isEqualTo("1689561600"); Assertions.assertThat(jsonNode.get("metadata").get("lsn").asText()).isEqualTo("178"); Assertions.assertThat(jsonNode.get("metadata").get("operationType").asText()).isEqualTo("replace"); Assertions.assertThat(jsonNode.get("metadata").get("previousImageLSN").asText()).isEqualTo("176"); Assertions.assertThat(jsonNode.get("metadata").get("timeToLiveExpired").asText()).isEqualTo("true"); ChangeFeedMetaData changeFeedMetaDataCaseOne = changeFeedProcessorItem.getChangeFeedMetaData(); Assertions.assertThat(changeFeedMetaDataCaseOne).isNotNull(); Assertions.assertThat(changeFeedMetaDataCaseOne.getConflictResolutionTimestamp()).isEqualTo(Instant.ofEpochSecond(1689561600)); Assertions.assertThat(changeFeedMetaDataCaseOne.getOperationType()).isEqualTo(ChangeFeedOperationType.REPLACE); Assertions.assertThat(changeFeedMetaDataCaseOne.getLogSequenceNumber()).isEqualTo(178); Assertions.assertThat(changeFeedMetaDataCaseOne.getPreviousLogSequenceNumber()).isEqualTo(176); Assertions.assertThat(changeFeedMetaDataCaseOne.isTimeToLiveExpired()).isEqualTo(true); json = "{\"current\":{\"id\":\"1946c04a-070b-48c0-8e36-517c8d2f92ed\",\"mypk\":\"mypk-1\",\"prop\":\"Gates\",\"_rid\":\"NopBALG34lcBAAAAAAAAAA==\",\"_self\":\"dbs/NopBAA==/colls/NopBALG34lc=/docs/NopBALG34lcBAAAAAAAAAA==/\",\"_etag\":\"\\\"00000000-0000-0000-b857-fda256f201d9\\\"\",\"_attachments\":\"attachments/\",\"_ts\":1689561604},\"metadata\":{\"lsn\":178,\"crts\":1689561608,\"operationType\":\"replace\",\"previousImageLSN\":176,\"timeToLiveExpired\": false}}"; changeFeedProcessorItem = simpleObjectMapper.readValue(json, ChangeFeedProcessorItem.class); jsonNode = changeFeedProcessorItem.toJsonNode(); Assertions.assertThat(jsonNode.get("metadata").get("crts").asText()).isEqualTo("1689561608"); Assertions.assertThat(jsonNode.get("metadata").get("lsn").asText()).isEqualTo("178"); Assertions.assertThat(jsonNode.get("metadata").get("operationType").asText()).isEqualTo("replace"); Assertions.assertThat(jsonNode.get("metadata").get("previousImageLSN").asText()).isEqualTo("176"); Assertions.assertThat(jsonNode.get("metadata").get("timeToLiveExpired").asText()).isEqualTo("false"); ChangeFeedMetaData changeFeedMetaDataCaseTwo = changeFeedProcessorItem.getChangeFeedMetaData(); Assertions.assertThat(changeFeedMetaDataCaseTwo).isNotNull(); Assertions.assertThat(changeFeedMetaDataCaseTwo.getConflictResolutionTimestamp()).isEqualTo(Instant.ofEpochSecond(1689561608)); Assertions.assertThat(changeFeedMetaDataCaseTwo.getOperationType()).isEqualTo(ChangeFeedOperationType.REPLACE); Assertions.assertThat(changeFeedMetaDataCaseTwo.getLogSequenceNumber()).isEqualTo(178); Assertions.assertThat(changeFeedMetaDataCaseTwo.getPreviousLogSequenceNumber()).isEqualTo(176); Assertions.assertThat(changeFeedMetaDataCaseTwo.isTimeToLiveExpired()).isEqualTo(false); }
class ChangeFeedProcessorItemSerializerTest { private final static Logger logger = LoggerFactory.getLogger(ChangeFeedProcessorItemSerializerTest.class); private final ObjectMapper simpleObjectMapper = Utils.getSimpleObjectMapper(); @Test(groups = { "unit" }) public void testChangeFeedMetaDataDeSerializer() throws JsonProcessingException { String json = "{\"lsn\":68,\"crts\":1689555410,\"operationType\":\"replace\",\"previousImageLSN\":66}"; JsonNode jsonNode = simpleObjectMapper.readValue(json, JsonNode.class); Assertions.assertThat(jsonNode.get("crts").asText()).isEqualTo("1689555410"); } @Test(groups = { "unit" }) public void testCreateChangeFeedProcessorItemDeSerializer() throws JsonProcessingException { String json = "{\"current\":{\"id\":\"1946c04a-070b-48c0-8e36-517c8d2f92ed\",\"mypk\":\"mypk-1\",\"prop\":\"Johnson\",\"_rid\":\"NopBALG34lcBAAAAAAAAAA==\",\"_self\":\"dbs/NopBAA==/colls/NopBALG34lc=/docs/NopBALG34lcBAAAAAAAAAA==/\",\"_etag\":\"\\\"00000000-0000-0000-b857-fd9e73fb01d9\\\"\",\"_attachments\":\"attachments/\",\"_ts\":1689561604},\"metadata\":{\"lsn\":176,\"crts\":1689561600,\"operationType\":\"create\"}}"; ChangeFeedProcessorItem changeFeedProcessorItem = simpleObjectMapper.readValue(json, ChangeFeedProcessorItem.class); JsonNode jsonNode = changeFeedProcessorItem.toJsonNode(); Assertions.assertThat(jsonNode.get("metadata").get("crts").asText()).isEqualTo("1689561600"); } @Test(groups = { "unit" }) }
class ChangeFeedProcessorItemSerializerTest { private final ObjectMapper simpleObjectMapper = Utils.getSimpleObjectMapper(); @Test(groups = { "unit" }) public void testChangeFeedMetaDataDeSerializer() throws JsonProcessingException { String json = "{\"lsn\":68,\"crts\":1689555410,\"operationType\":\"replace\",\"previousImageLSN\":66}"; ChangeFeedMetaData changeFeedMetaData = simpleObjectMapper.readValue(json, ChangeFeedMetaData.class); JsonNode jsonNode = simpleObjectMapper.readValue(json, JsonNode.class); Assertions.assertThat(changeFeedMetaData.getConflictResolutionTimestamp()).isEqualTo(Instant.ofEpochSecond(1689555410)); Assertions.assertThat(jsonNode.get("crts").asText()).isEqualTo("1689555410"); jsonNode = simpleObjectMapper.convertValue(changeFeedMetaData, JsonNode.class); Assertions.assertThat(jsonNode.get("crts").asText()).isEqualTo("1689555410"); json = "{\"lsn\":68,\"crts\":1689555412,\"operationType\":\"replace\",\"previousImageLSN\":66}"; changeFeedMetaData = simpleObjectMapper.readValue(json, ChangeFeedMetaData.class); jsonNode = simpleObjectMapper.readValue(json, JsonNode.class); Assertions.assertThat(changeFeedMetaData.getConflictResolutionTimestamp()).isEqualTo(Instant.ofEpochSecond(1689555412)); Assertions.assertThat(jsonNode.get("crts").asText()).isEqualTo("1689555412"); jsonNode = simpleObjectMapper.convertValue(changeFeedMetaData, JsonNode.class); Assertions.assertThat(jsonNode.get("crts").asText()).isEqualTo("1689555412"); } @Test(groups = { "unit" }) public void testCreateChangeFeedProcessorItemDeSerializer() throws JsonProcessingException { String json = "{\"current\":{\"id\":\"1946c04a-070b-48c0-8e36-517c8d2f92ed\",\"mypk\":\"mypk-1\",\"prop\":\"Johnson\",\"_rid\":\"NopBALG34lcBAAAAAAAAAA==\",\"_self\":\"dbs/NopBAA==/colls/NopBALG34lc=/docs/NopBALG34lcBAAAAAAAAAA==/\",\"_etag\":\"\\\"00000000-0000-0000-b857-fd9e73fb01d9\\\"\",\"_attachments\":\"attachments/\",\"_ts\":1689561604},\"metadata\":{\"lsn\":176,\"crts\":1689561600,\"operationType\":\"create\"}}"; ChangeFeedProcessorItem changeFeedProcessorItem = simpleObjectMapper.readValue(json, ChangeFeedProcessorItem.class); JsonNode jsonNode = changeFeedProcessorItem.toJsonNode(); Assertions.assertThat(jsonNode.get("metadata").get("crts").asText()).isEqualTo("1689561600"); Assertions.assertThat(jsonNode.get("metadata").get("lsn").asText()).isEqualTo("176"); Assertions.assertThat(jsonNode.get("metadata").get("operationType").asText()).isEqualTo("create"); Assertions.assertThat(jsonNode.get("metadata").get("previousImageLSN")).isNull(); Assertions.assertThat(jsonNode.get("metadata").get("timeToLiveExpired")).isNull(); ChangeFeedMetaData changeFeedMetaDataCaseOne = changeFeedProcessorItem.getChangeFeedMetaData(); Assertions.assertThat(changeFeedMetaDataCaseOne).isNotNull(); Assertions.assertThat(changeFeedMetaDataCaseOne.getConflictResolutionTimestamp()).isEqualTo(Instant.ofEpochSecond(1689561600)); Assertions.assertThat(changeFeedMetaDataCaseOne.getOperationType()).isEqualTo(ChangeFeedOperationType.CREATE); Assertions.assertThat(changeFeedMetaDataCaseOne.getLogSequenceNumber()).isEqualTo(176); Assertions.assertThat(changeFeedMetaDataCaseOne.getPreviousLogSequenceNumber()).isEqualTo(0); Assertions.assertThat(changeFeedMetaDataCaseOne.isTimeToLiveExpired()).isEqualTo(false); json = "{\"current\":{\"id\":\"1946c04a-070b-48c0-8e36-517c8d2f92ed\",\"mypk\":\"mypk-1\",\"prop\":\"Johnson\",\"_rid\":\"NopBALG34lcBAAAAAAAAAA==\",\"_self\":\"dbs/NopBAA==/colls/NopBALG34lc=/docs/NopBALG34lcBAAAAAAAAAA==/\",\"_etag\":\"\\\"00000000-0000-0000-b857-fd9e73fb01d9\\\"\",\"_attachments\":\"attachments/\",\"_ts\":1689561604},\"metadata\":{\"lsn\":176,\"crts\":1689561605,\"operationType\":\"create\"}}"; changeFeedProcessorItem = simpleObjectMapper.readValue(json, ChangeFeedProcessorItem.class); jsonNode = changeFeedProcessorItem.toJsonNode(); Assertions.assertThat(jsonNode.get("metadata").get("crts").asText()).isEqualTo("1689561605"); Assertions.assertThat(jsonNode.get("metadata").get("lsn").asText()).isEqualTo("176"); Assertions.assertThat(jsonNode.get("metadata").get("operationType").asText()).isEqualTo("create"); Assertions.assertThat(jsonNode.get("metadata").get("previousImageLSN")).isNull(); Assertions.assertThat(jsonNode.get("metadata").get("timeToLiveExpired")).isNull(); ChangeFeedMetaData changeFeedMetaDataCaseTwo = changeFeedProcessorItem.getChangeFeedMetaData(); Assertions.assertThat(changeFeedMetaDataCaseTwo).isNotNull(); Assertions.assertThat(changeFeedMetaDataCaseTwo.getConflictResolutionTimestamp()).isEqualTo(Instant.ofEpochSecond(1689561605)); Assertions.assertThat(changeFeedMetaDataCaseTwo.getOperationType()).isEqualTo(ChangeFeedOperationType.CREATE); Assertions.assertThat(changeFeedMetaDataCaseTwo.getLogSequenceNumber()).isEqualTo(176); Assertions.assertThat(changeFeedMetaDataCaseTwo.getPreviousLogSequenceNumber()).isEqualTo(0); Assertions.assertThat(changeFeedMetaDataCaseTwo.isTimeToLiveExpired()).isEqualTo(false); } @Test(groups = { "unit" }) @Test(groups = { "unit" }) public void testDeleteChangeFeedProcessorItemDeSerializer() throws JsonProcessingException { String json = "{\"current\":{\"id\":\"1946c04a-070b-48c0-8e36-517c8d2f92ed\",\"mypk\":\"mypk-1\",\"prop\":\"Gates\",\"_rid\":\"NopBALG34lcBAAAAAAAAAA==\",\"_self\":\"dbs/NopBAA==/colls/NopBALG34lc=/docs/NopBALG34lcBAAAAAAAAAA==/\",\"_etag\":\"\\\"00000000-0000-0000-b857-fda256f201d9\\\"\",\"_attachments\":\"attachments/\",\"_ts\":1689561604},\"metadata\":{\"lsn\":178,\"crts\":1689561600,\"operationType\":\"delete\",\"previousImageLSN\":176}}"; ChangeFeedProcessorItem changeFeedProcessorItem = simpleObjectMapper.readValue(json, ChangeFeedProcessorItem.class); JsonNode jsonNode = changeFeedProcessorItem.toJsonNode(); Assertions.assertThat(jsonNode.get("metadata").get("crts").asText()).isEqualTo("1689561600"); Assertions.assertThat(jsonNode.get("metadata").get("lsn").asText()).isEqualTo("178"); Assertions.assertThat(jsonNode.get("metadata").get("operationType").asText()).isEqualTo("delete"); Assertions.assertThat(jsonNode.get("metadata").get("previousImageLSN").asText()).isEqualTo("176"); Assertions.assertThat(jsonNode.get("metadata").get("timeToLiveExpired")).isNull(); ChangeFeedMetaData changeFeedMetaDataCaseOne = changeFeedProcessorItem.getChangeFeedMetaData(); Assertions.assertThat(changeFeedMetaDataCaseOne).isNotNull(); Assertions.assertThat(changeFeedMetaDataCaseOne.getConflictResolutionTimestamp()).isEqualTo(Instant.ofEpochSecond(1689561600)); Assertions.assertThat(changeFeedMetaDataCaseOne.getOperationType()).isEqualTo(ChangeFeedOperationType.DELETE); Assertions.assertThat(changeFeedMetaDataCaseOne.getLogSequenceNumber()).isEqualTo(178); Assertions.assertThat(changeFeedMetaDataCaseOne.getPreviousLogSequenceNumber()).isEqualTo(176); json = "{\"current\":{\"id\":\"1946c04a-070b-48c0-8e36-517c8d2f92ed\",\"mypk\":\"mypk-1\",\"prop\":\"Gates\",\"_rid\":\"NopBALG34lcBAAAAAAAAAA==\",\"_self\":\"dbs/NopBAA==/colls/NopBALG34lc=/docs/NopBALG34lcBAAAAAAAAAA==/\",\"_etag\":\"\\\"00000000-0000-0000-b857-fda256f201d9\\\"\",\"_attachments\":\"attachments/\",\"_ts\":1689561604},\"metadata\":{\"lsn\":178,\"crts\":1689561608,\"operationType\":\"delete\",\"previousImageLSN\":176}}"; changeFeedProcessorItem = simpleObjectMapper.readValue(json, ChangeFeedProcessorItem.class); jsonNode = changeFeedProcessorItem.toJsonNode(); Assertions.assertThat(jsonNode.get("metadata").get("crts").asText()).isEqualTo("1689561608"); Assertions.assertThat(jsonNode.get("metadata").get("lsn").asText()).isEqualTo("178"); Assertions.assertThat(jsonNode.get("metadata").get("operationType").asText()).isEqualTo("delete"); Assertions.assertThat(jsonNode.get("metadata").get("previousImageLSN").asText()).isEqualTo("176"); Assertions.assertThat(jsonNode.get("metadata").get("timeToLiveExpired")).isNull(); ChangeFeedMetaData changeFeedMetaDataCaseTwo = changeFeedProcessorItem.getChangeFeedMetaData(); Assertions.assertThat(changeFeedMetaDataCaseTwo).isNotNull(); Assertions.assertThat(changeFeedMetaDataCaseTwo.getConflictResolutionTimestamp()).isEqualTo(Instant.ofEpochSecond(1689561608)); Assertions.assertThat(changeFeedMetaDataCaseTwo.getOperationType()).isEqualTo(ChangeFeedOperationType.DELETE); Assertions.assertThat(changeFeedMetaDataCaseTwo.getLogSequenceNumber()).isEqualTo(178); Assertions.assertThat(changeFeedMetaDataCaseTwo.getPreviousLogSequenceNumber()).isEqualTo(176); } }
Added more in next iteration.
public void testReplaceChangeFeedProcessorItemDeSerializer() throws JsonProcessingException { String json = "{\"current\":{\"id\":\"1946c04a-070b-48c0-8e36-517c8d2f92ed\",\"mypk\":\"mypk-1\",\"prop\":\"Gates\",\"_rid\":\"NopBALG34lcBAAAAAAAAAA==\",\"_self\":\"dbs/NopBAA==/colls/NopBALG34lc=/docs/NopBALG34lcBAAAAAAAAAA==/\",\"_etag\":\"\\\"00000000-0000-0000-b857-fda256f201d9\\\"\",\"_attachments\":\"attachments/\",\"_ts\":1689561604},\"metadata\":{\"lsn\":178,\"crts\":1689561600,\"operationType\":\"replace\",\"previousImageLSN\":176}}"; ChangeFeedProcessorItem changeFeedProcessorItem = simpleObjectMapper.readValue(json, ChangeFeedProcessorItem.class); JsonNode jsonNode = changeFeedProcessorItem.toJsonNode(); Assertions.assertThat(jsonNode.get("metadata").get("crts").asText()).isEqualTo("1689561600"); }
}
public void testReplaceChangeFeedProcessorItemDeSerializer() throws JsonProcessingException { String json = "{\"current\":{\"id\":\"1946c04a-070b-48c0-8e36-517c8d2f92ed\",\"mypk\":\"mypk-1\",\"prop\":\"Gates\",\"_rid\":\"NopBALG34lcBAAAAAAAAAA==\",\"_self\":\"dbs/NopBAA==/colls/NopBALG34lc=/docs/NopBALG34lcBAAAAAAAAAA==/\",\"_etag\":\"\\\"00000000-0000-0000-b857-fda256f201d9\\\"\",\"_attachments\":\"attachments/\",\"_ts\":1689561604},\"metadata\":{\"lsn\":178,\"crts\":1689561600,\"operationType\":\"replace\",\"previousImageLSN\":176,\"timeToLiveExpired\": true}}"; ChangeFeedProcessorItem changeFeedProcessorItem = simpleObjectMapper.readValue(json, ChangeFeedProcessorItem.class); JsonNode jsonNode = changeFeedProcessorItem.toJsonNode(); Assertions.assertThat(jsonNode.get("metadata").get("crts").asText()).isEqualTo("1689561600"); Assertions.assertThat(jsonNode.get("metadata").get("lsn").asText()).isEqualTo("178"); Assertions.assertThat(jsonNode.get("metadata").get("operationType").asText()).isEqualTo("replace"); Assertions.assertThat(jsonNode.get("metadata").get("previousImageLSN").asText()).isEqualTo("176"); Assertions.assertThat(jsonNode.get("metadata").get("timeToLiveExpired").asText()).isEqualTo("true"); ChangeFeedMetaData changeFeedMetaDataCaseOne = changeFeedProcessorItem.getChangeFeedMetaData(); Assertions.assertThat(changeFeedMetaDataCaseOne).isNotNull(); Assertions.assertThat(changeFeedMetaDataCaseOne.getConflictResolutionTimestamp()).isEqualTo(Instant.ofEpochSecond(1689561600)); Assertions.assertThat(changeFeedMetaDataCaseOne.getOperationType()).isEqualTo(ChangeFeedOperationType.REPLACE); Assertions.assertThat(changeFeedMetaDataCaseOne.getLogSequenceNumber()).isEqualTo(178); Assertions.assertThat(changeFeedMetaDataCaseOne.getPreviousLogSequenceNumber()).isEqualTo(176); Assertions.assertThat(changeFeedMetaDataCaseOne.isTimeToLiveExpired()).isEqualTo(true); json = "{\"current\":{\"id\":\"1946c04a-070b-48c0-8e36-517c8d2f92ed\",\"mypk\":\"mypk-1\",\"prop\":\"Gates\",\"_rid\":\"NopBALG34lcBAAAAAAAAAA==\",\"_self\":\"dbs/NopBAA==/colls/NopBALG34lc=/docs/NopBALG34lcBAAAAAAAAAA==/\",\"_etag\":\"\\\"00000000-0000-0000-b857-fda256f201d9\\\"\",\"_attachments\":\"attachments/\",\"_ts\":1689561604},\"metadata\":{\"lsn\":178,\"crts\":1689561608,\"operationType\":\"replace\",\"previousImageLSN\":176,\"timeToLiveExpired\": false}}"; changeFeedProcessorItem = simpleObjectMapper.readValue(json, ChangeFeedProcessorItem.class); jsonNode = changeFeedProcessorItem.toJsonNode(); Assertions.assertThat(jsonNode.get("metadata").get("crts").asText()).isEqualTo("1689561608"); Assertions.assertThat(jsonNode.get("metadata").get("lsn").asText()).isEqualTo("178"); Assertions.assertThat(jsonNode.get("metadata").get("operationType").asText()).isEqualTo("replace"); Assertions.assertThat(jsonNode.get("metadata").get("previousImageLSN").asText()).isEqualTo("176"); Assertions.assertThat(jsonNode.get("metadata").get("timeToLiveExpired").asText()).isEqualTo("false"); ChangeFeedMetaData changeFeedMetaDataCaseTwo = changeFeedProcessorItem.getChangeFeedMetaData(); Assertions.assertThat(changeFeedMetaDataCaseTwo).isNotNull(); Assertions.assertThat(changeFeedMetaDataCaseTwo.getConflictResolutionTimestamp()).isEqualTo(Instant.ofEpochSecond(1689561608)); Assertions.assertThat(changeFeedMetaDataCaseTwo.getOperationType()).isEqualTo(ChangeFeedOperationType.REPLACE); Assertions.assertThat(changeFeedMetaDataCaseTwo.getLogSequenceNumber()).isEqualTo(178); Assertions.assertThat(changeFeedMetaDataCaseTwo.getPreviousLogSequenceNumber()).isEqualTo(176); Assertions.assertThat(changeFeedMetaDataCaseTwo.isTimeToLiveExpired()).isEqualTo(false); }
class ChangeFeedProcessorItemSerializerTest { private final static Logger logger = LoggerFactory.getLogger(ChangeFeedProcessorItemSerializerTest.class); private final ObjectMapper simpleObjectMapper = Utils.getSimpleObjectMapper(); @Test(groups = { "unit" }) public void testChangeFeedMetaDataDeSerializer() throws JsonProcessingException { String json = "{\"lsn\":68,\"crts\":1689555410,\"operationType\":\"replace\",\"previousImageLSN\":66}"; JsonNode jsonNode = simpleObjectMapper.readValue(json, JsonNode.class); Assertions.assertThat(jsonNode.get("crts").asText()).isEqualTo("1689555410"); } @Test(groups = { "unit" }) public void testCreateChangeFeedProcessorItemDeSerializer() throws JsonProcessingException { String json = "{\"current\":{\"id\":\"1946c04a-070b-48c0-8e36-517c8d2f92ed\",\"mypk\":\"mypk-1\",\"prop\":\"Johnson\",\"_rid\":\"NopBALG34lcBAAAAAAAAAA==\",\"_self\":\"dbs/NopBAA==/colls/NopBALG34lc=/docs/NopBALG34lcBAAAAAAAAAA==/\",\"_etag\":\"\\\"00000000-0000-0000-b857-fd9e73fb01d9\\\"\",\"_attachments\":\"attachments/\",\"_ts\":1689561604},\"metadata\":{\"lsn\":176,\"crts\":1689561600,\"operationType\":\"create\"}}"; ChangeFeedProcessorItem changeFeedProcessorItem = simpleObjectMapper.readValue(json, ChangeFeedProcessorItem.class); JsonNode jsonNode = changeFeedProcessorItem.toJsonNode(); Assertions.assertThat(jsonNode.get("metadata").get("crts").asText()).isEqualTo("1689561600"); } @Test(groups = { "unit" }) }
class ChangeFeedProcessorItemSerializerTest { private final ObjectMapper simpleObjectMapper = Utils.getSimpleObjectMapper(); @Test(groups = { "unit" }) public void testChangeFeedMetaDataDeSerializer() throws JsonProcessingException { String json = "{\"lsn\":68,\"crts\":1689555410,\"operationType\":\"replace\",\"previousImageLSN\":66}"; ChangeFeedMetaData changeFeedMetaData = simpleObjectMapper.readValue(json, ChangeFeedMetaData.class); JsonNode jsonNode = simpleObjectMapper.readValue(json, JsonNode.class); Assertions.assertThat(changeFeedMetaData.getConflictResolutionTimestamp()).isEqualTo(Instant.ofEpochSecond(1689555410)); Assertions.assertThat(jsonNode.get("crts").asText()).isEqualTo("1689555410"); jsonNode = simpleObjectMapper.convertValue(changeFeedMetaData, JsonNode.class); Assertions.assertThat(jsonNode.get("crts").asText()).isEqualTo("1689555410"); json = "{\"lsn\":68,\"crts\":1689555412,\"operationType\":\"replace\",\"previousImageLSN\":66}"; changeFeedMetaData = simpleObjectMapper.readValue(json, ChangeFeedMetaData.class); jsonNode = simpleObjectMapper.readValue(json, JsonNode.class); Assertions.assertThat(changeFeedMetaData.getConflictResolutionTimestamp()).isEqualTo(Instant.ofEpochSecond(1689555412)); Assertions.assertThat(jsonNode.get("crts").asText()).isEqualTo("1689555412"); jsonNode = simpleObjectMapper.convertValue(changeFeedMetaData, JsonNode.class); Assertions.assertThat(jsonNode.get("crts").asText()).isEqualTo("1689555412"); } @Test(groups = { "unit" }) public void testCreateChangeFeedProcessorItemDeSerializer() throws JsonProcessingException { String json = "{\"current\":{\"id\":\"1946c04a-070b-48c0-8e36-517c8d2f92ed\",\"mypk\":\"mypk-1\",\"prop\":\"Johnson\",\"_rid\":\"NopBALG34lcBAAAAAAAAAA==\",\"_self\":\"dbs/NopBAA==/colls/NopBALG34lc=/docs/NopBALG34lcBAAAAAAAAAA==/\",\"_etag\":\"\\\"00000000-0000-0000-b857-fd9e73fb01d9\\\"\",\"_attachments\":\"attachments/\",\"_ts\":1689561604},\"metadata\":{\"lsn\":176,\"crts\":1689561600,\"operationType\":\"create\"}}"; ChangeFeedProcessorItem changeFeedProcessorItem = simpleObjectMapper.readValue(json, ChangeFeedProcessorItem.class); JsonNode jsonNode = changeFeedProcessorItem.toJsonNode(); Assertions.assertThat(jsonNode.get("metadata").get("crts").asText()).isEqualTo("1689561600"); Assertions.assertThat(jsonNode.get("metadata").get("lsn").asText()).isEqualTo("176"); Assertions.assertThat(jsonNode.get("metadata").get("operationType").asText()).isEqualTo("create"); Assertions.assertThat(jsonNode.get("metadata").get("previousImageLSN")).isNull(); Assertions.assertThat(jsonNode.get("metadata").get("timeToLiveExpired")).isNull(); ChangeFeedMetaData changeFeedMetaDataCaseOne = changeFeedProcessorItem.getChangeFeedMetaData(); Assertions.assertThat(changeFeedMetaDataCaseOne).isNotNull(); Assertions.assertThat(changeFeedMetaDataCaseOne.getConflictResolutionTimestamp()).isEqualTo(Instant.ofEpochSecond(1689561600)); Assertions.assertThat(changeFeedMetaDataCaseOne.getOperationType()).isEqualTo(ChangeFeedOperationType.CREATE); Assertions.assertThat(changeFeedMetaDataCaseOne.getLogSequenceNumber()).isEqualTo(176); Assertions.assertThat(changeFeedMetaDataCaseOne.getPreviousLogSequenceNumber()).isEqualTo(0); Assertions.assertThat(changeFeedMetaDataCaseOne.isTimeToLiveExpired()).isEqualTo(false); json = "{\"current\":{\"id\":\"1946c04a-070b-48c0-8e36-517c8d2f92ed\",\"mypk\":\"mypk-1\",\"prop\":\"Johnson\",\"_rid\":\"NopBALG34lcBAAAAAAAAAA==\",\"_self\":\"dbs/NopBAA==/colls/NopBALG34lc=/docs/NopBALG34lcBAAAAAAAAAA==/\",\"_etag\":\"\\\"00000000-0000-0000-b857-fd9e73fb01d9\\\"\",\"_attachments\":\"attachments/\",\"_ts\":1689561604},\"metadata\":{\"lsn\":176,\"crts\":1689561605,\"operationType\":\"create\"}}"; changeFeedProcessorItem = simpleObjectMapper.readValue(json, ChangeFeedProcessorItem.class); jsonNode = changeFeedProcessorItem.toJsonNode(); Assertions.assertThat(jsonNode.get("metadata").get("crts").asText()).isEqualTo("1689561605"); Assertions.assertThat(jsonNode.get("metadata").get("lsn").asText()).isEqualTo("176"); Assertions.assertThat(jsonNode.get("metadata").get("operationType").asText()).isEqualTo("create"); Assertions.assertThat(jsonNode.get("metadata").get("previousImageLSN")).isNull(); Assertions.assertThat(jsonNode.get("metadata").get("timeToLiveExpired")).isNull(); ChangeFeedMetaData changeFeedMetaDataCaseTwo = changeFeedProcessorItem.getChangeFeedMetaData(); Assertions.assertThat(changeFeedMetaDataCaseTwo).isNotNull(); Assertions.assertThat(changeFeedMetaDataCaseTwo.getConflictResolutionTimestamp()).isEqualTo(Instant.ofEpochSecond(1689561605)); Assertions.assertThat(changeFeedMetaDataCaseTwo.getOperationType()).isEqualTo(ChangeFeedOperationType.CREATE); Assertions.assertThat(changeFeedMetaDataCaseTwo.getLogSequenceNumber()).isEqualTo(176); Assertions.assertThat(changeFeedMetaDataCaseTwo.getPreviousLogSequenceNumber()).isEqualTo(0); Assertions.assertThat(changeFeedMetaDataCaseTwo.isTimeToLiveExpired()).isEqualTo(false); } @Test(groups = { "unit" }) @Test(groups = { "unit" }) public void testDeleteChangeFeedProcessorItemDeSerializer() throws JsonProcessingException { String json = "{\"current\":{\"id\":\"1946c04a-070b-48c0-8e36-517c8d2f92ed\",\"mypk\":\"mypk-1\",\"prop\":\"Gates\",\"_rid\":\"NopBALG34lcBAAAAAAAAAA==\",\"_self\":\"dbs/NopBAA==/colls/NopBALG34lc=/docs/NopBALG34lcBAAAAAAAAAA==/\",\"_etag\":\"\\\"00000000-0000-0000-b857-fda256f201d9\\\"\",\"_attachments\":\"attachments/\",\"_ts\":1689561604},\"metadata\":{\"lsn\":178,\"crts\":1689561600,\"operationType\":\"delete\",\"previousImageLSN\":176}}"; ChangeFeedProcessorItem changeFeedProcessorItem = simpleObjectMapper.readValue(json, ChangeFeedProcessorItem.class); JsonNode jsonNode = changeFeedProcessorItem.toJsonNode(); Assertions.assertThat(jsonNode.get("metadata").get("crts").asText()).isEqualTo("1689561600"); Assertions.assertThat(jsonNode.get("metadata").get("lsn").asText()).isEqualTo("178"); Assertions.assertThat(jsonNode.get("metadata").get("operationType").asText()).isEqualTo("delete"); Assertions.assertThat(jsonNode.get("metadata").get("previousImageLSN").asText()).isEqualTo("176"); Assertions.assertThat(jsonNode.get("metadata").get("timeToLiveExpired")).isNull(); ChangeFeedMetaData changeFeedMetaDataCaseOne = changeFeedProcessorItem.getChangeFeedMetaData(); Assertions.assertThat(changeFeedMetaDataCaseOne).isNotNull(); Assertions.assertThat(changeFeedMetaDataCaseOne.getConflictResolutionTimestamp()).isEqualTo(Instant.ofEpochSecond(1689561600)); Assertions.assertThat(changeFeedMetaDataCaseOne.getOperationType()).isEqualTo(ChangeFeedOperationType.DELETE); Assertions.assertThat(changeFeedMetaDataCaseOne.getLogSequenceNumber()).isEqualTo(178); Assertions.assertThat(changeFeedMetaDataCaseOne.getPreviousLogSequenceNumber()).isEqualTo(176); json = "{\"current\":{\"id\":\"1946c04a-070b-48c0-8e36-517c8d2f92ed\",\"mypk\":\"mypk-1\",\"prop\":\"Gates\",\"_rid\":\"NopBALG34lcBAAAAAAAAAA==\",\"_self\":\"dbs/NopBAA==/colls/NopBALG34lc=/docs/NopBALG34lcBAAAAAAAAAA==/\",\"_etag\":\"\\\"00000000-0000-0000-b857-fda256f201d9\\\"\",\"_attachments\":\"attachments/\",\"_ts\":1689561604},\"metadata\":{\"lsn\":178,\"crts\":1689561608,\"operationType\":\"delete\",\"previousImageLSN\":176}}"; changeFeedProcessorItem = simpleObjectMapper.readValue(json, ChangeFeedProcessorItem.class); jsonNode = changeFeedProcessorItem.toJsonNode(); Assertions.assertThat(jsonNode.get("metadata").get("crts").asText()).isEqualTo("1689561608"); Assertions.assertThat(jsonNode.get("metadata").get("lsn").asText()).isEqualTo("178"); Assertions.assertThat(jsonNode.get("metadata").get("operationType").asText()).isEqualTo("delete"); Assertions.assertThat(jsonNode.get("metadata").get("previousImageLSN").asText()).isEqualTo("176"); Assertions.assertThat(jsonNode.get("metadata").get("timeToLiveExpired")).isNull(); ChangeFeedMetaData changeFeedMetaDataCaseTwo = changeFeedProcessorItem.getChangeFeedMetaData(); Assertions.assertThat(changeFeedMetaDataCaseTwo).isNotNull(); Assertions.assertThat(changeFeedMetaDataCaseTwo.getConflictResolutionTimestamp()).isEqualTo(Instant.ofEpochSecond(1689561608)); Assertions.assertThat(changeFeedMetaDataCaseTwo.getOperationType()).isEqualTo(ChangeFeedOperationType.DELETE); Assertions.assertThat(changeFeedMetaDataCaseTwo.getLogSequenceNumber()).isEqualTo(178); Assertions.assertThat(changeFeedMetaDataCaseTwo.getPreviousLogSequenceNumber()).isEqualTo(176); } }
We don't need to convert, we can create an ObjectNode and then set current, previous and metadata.
public JsonNode toJsonNode() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = Utils.getSimpleObjectMapper().convertValue(this, JsonNode.class); } ChangeFeedProcessorItem changeFeedProcessorItem = new ChangeFeedProcessorItem(this.changeFeedProcessorItemAsJsonNode); if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = new ChangeFeedMetaData(changeFeedProcessorItem.changeFeedMetaData); } return Utils.getSimpleObjectMapper().convertValue(changeFeedProcessorItem, JsonNode.class); }
this.changeFeedProcessorItemAsJsonNode = Utils.getSimpleObjectMapper().convertValue(this, JsonNode.class);
public JsonNode toJsonNode() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return this.changeFeedProcessorItemAsJsonNode; }
class ChangeFeedProcessorItem { private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); @JsonProperty("current") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode current; @JsonProperty("previous") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode previous; @JsonProperty("metadata") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode changeFeedMetaData; private ChangeFeedMetaData changeFeedMetaDataInternal; private JsonNode changeFeedProcessorItemAsJsonNode; /** * Constructor * */ public ChangeFeedProcessorItem() {} ChangeFeedProcessorItem(JsonNode changeFeedProcessorItemAsJsonNode) { this.current = changeFeedProcessorItemAsJsonNode.get("current"); this.previous = changeFeedProcessorItemAsJsonNode.get("previous"); this.changeFeedMetaData = changeFeedProcessorItemAsJsonNode.get("metadata"); } /** * Gets the change feed current item. * * @return change feed current item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getCurrent() { return current; } /** * Gets the change feed previous item. * For delete operations, previous image is always going to be provided. * The previous image on replace operations is not going to be exposed by default and requires account-level or container-level opt-in. * * @return change feed previous item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getPrevious() { return previous; } /** * Gets the change feed metadata. * * @return change feed metadata. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @JsonIgnore public ChangeFeedMetaData getChangeFeedMetaData() { if (changeFeedMetaDataInternal == null) { changeFeedMetaDataInternal = new ChangeFeedMetaData(this.changeFeedMetaData); } return changeFeedMetaDataInternal; } /** * Helper API to convert this changeFeedProcessorItem instance to raw JsonNode format. * * @return jsonNode format of this changeFeedProcessorItem instance. * * @throws IllegalArgumentException If conversion fails due to incompatible type; * if so, root cause will contain underlying checked exception data binding functionality threw */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @Override public String toString() { try { return Utils.getSimpleObjectMapper().writeValueAsString(this); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert object to string", e); } } }
class ChangeFeedProcessorItem { @JsonProperty("current") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode current; @JsonProperty("previous") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode previous; @JsonProperty("metadata") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode changeFeedMetaData; private ChangeFeedMetaData changeFeedMetaDataInternal; private JsonNode changeFeedProcessorItemAsJsonNode; /** * Gets the change feed current item. * * @return change feed current item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getCurrent() { return current; } /** * Gets the change feed previous item. * For delete operations, previous image is always going to be provided. * The previous image on replace operations is not going to be exposed by default and requires account-level or container-level opt-in. * * @return change feed previous item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getPrevious() { return previous; } /** * Gets the change feed metadata. * * @return change feed metadata. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @JsonIgnore public ChangeFeedMetaData getChangeFeedMetaData() { if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class); } return this.changeFeedMetaDataInternal; } /** * Helper API to convert this changeFeedProcessorItem instance to raw JsonNode format. * * @return jsonNode format of this changeFeedProcessorItem instance. * * @throws IllegalArgumentException If conversion fails due to incompatible type; * if so, root cause will contain underlying checked exception data binding functionality threw */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @Override public String toString() { try { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return Utils.getSimpleObjectMapper().writeValueAsString(this.changeFeedProcessorItemAsJsonNode); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert object to string", e); } } private JsonNode constructChangeFeedProcessorItemAsJsonNode() { ObjectNode objectNode = Utils.getSimpleObjectMapper().createObjectNode(); if (this.previous != null) { objectNode.set("previous", this.previous); } if (this.current != null) { objectNode.set("current", this.current); } if (this.changeFeedMetaData != null) { objectNode.set("metadata", this.changeFeedMetaData); } return objectNode; } }
Sanitizers are to be added in both Record and Playback mode. <img width="563" alt="image" src="https://github.com/Azure/azure-sdk-for-java/assets/16845631/11b47561-a58e-4a28-bc29-d755a4e8eddc">
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( MapsRenderClientBuilder.RENDER_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
if (interceptorManager.isRecordMode()) {
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode() || interceptorManager.isPlaybackMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( MapsRenderClientBuilder.RENDER_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
class MapsRenderClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } MapsRenderClientBuilder getRenderAsyncClientBuilder(HttpClient httpClient, MapsRenderServiceVersion serviceVersion) { MapsRenderClientBuilder builder = new MapsRenderClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetMapTile(byte[] actual) { assertNotNull(actual); assertTrue(actual.length > 0); } static void validateGetMapTileWithResponse(int expectedStatusCode, Response<BinaryData> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapTile(response.getValue().toBytes()); } static void validateGetMapTileset(MapTileset expected, MapTileset actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getMinZoom(), actual.getMinZoom()); } static void validateGetMapTilesetWithResponse(MapTileset expected, int expectedStatusCode, Response<MapTileset> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapTileset(expected, response.getValue()); } static void validateGetMapAttribution(MapAttribution expected, MapAttribution actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCopyrights().size(), actual.getCopyrights().size()); } static void validateGetMapAttributionWithResponse(MapAttribution expected, int expectedStatusCode, Response<MapAttribution> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapAttribution(expected, response.getValue()); } static void validateGetCopyrightCaption(CopyrightCaption expected, CopyrightCaption actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); } static void validateGetCopyrightCaptionWithResponse(CopyrightCaption expected, int expectedStatusCode, Response<CopyrightCaption> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightCaption(expected, response.getValue()); } static void validateGetCopyrightCaptionFromBoundingBox(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); assertEquals(expected.getRegions().size(), actual.getRegions().size()); } static void validateGetCopyrightCaptionFromBoundingBoxWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightCaptionFromBoundingBox(expected, response.getValue()); } static void validateGetMapStaticImage(byte[] actual) { assertNotNull(actual); assertTrue(actual.length > 0); } static void validateGetMapStaticImageWithResponse(int expectedStatusCode, Response<BinaryData> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapStaticImage(response.getValue().toBytes()); } static void validateGetCopyrightForTile(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); assertEquals(expected.getRegions().size(), actual.getRegions().size()); } static void validateGetCopyrightForTileWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightForTile(expected, response.getValue()); } static void validateGetCopyrightForWorld(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); } static void validateGetCopyrightForWorldWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightForWorld(expected, response.getValue()); } }
class MapsRenderClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } MapsRenderClientBuilder getRenderAsyncClientBuilder(HttpClient httpClient, MapsRenderServiceVersion serviceVersion) { MapsRenderClientBuilder builder = new MapsRenderClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetMapTile(byte[] actual) { assertNotNull(actual); assertTrue(actual.length > 0); } static void validateGetMapTileWithResponse(int expectedStatusCode, Response<BinaryData> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapTile(response.getValue().toBytes()); } static void validateGetMapTileset(MapTileset expected, MapTileset actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getMinZoom(), actual.getMinZoom()); } static void validateGetMapTilesetWithResponse(MapTileset expected, int expectedStatusCode, Response<MapTileset> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapTileset(expected, response.getValue()); } static void validateGetMapAttribution(MapAttribution expected, MapAttribution actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCopyrights().size(), actual.getCopyrights().size()); } static void validateGetMapAttributionWithResponse(MapAttribution expected, int expectedStatusCode, Response<MapAttribution> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapAttribution(expected, response.getValue()); } static void validateGetCopyrightCaption(CopyrightCaption expected, CopyrightCaption actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); } static void validateGetCopyrightCaptionWithResponse(CopyrightCaption expected, int expectedStatusCode, Response<CopyrightCaption> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightCaption(expected, response.getValue()); } static void validateGetCopyrightCaptionFromBoundingBox(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); assertEquals(expected.getRegions().size(), actual.getRegions().size()); } static void validateGetCopyrightCaptionFromBoundingBoxWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightCaptionFromBoundingBox(expected, response.getValue()); } static void validateGetMapStaticImage(byte[] actual) { assertNotNull(actual); assertTrue(actual.length > 0); } static void validateGetMapStaticImageWithResponse(int expectedStatusCode, Response<BinaryData> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapStaticImage(response.getValue().toBytes()); } static void validateGetCopyrightForTile(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); assertEquals(expected.getRegions().size(), actual.getRegions().size()); } static void validateGetCopyrightForTileWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightForTile(expected, response.getValue()); } static void validateGetCopyrightForWorld(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); } static void validateGetCopyrightForWorldWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightForWorld(expected, response.getValue()); } }
Fixed in next iteration.
public JsonNode toJsonNode() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = Utils.getSimpleObjectMapper().convertValue(this, JsonNode.class); } ChangeFeedProcessorItem changeFeedProcessorItem = new ChangeFeedProcessorItem(this.changeFeedProcessorItemAsJsonNode); if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = new ChangeFeedMetaData(changeFeedProcessorItem.changeFeedMetaData); } return Utils.getSimpleObjectMapper().convertValue(changeFeedProcessorItem, JsonNode.class); }
this.changeFeedProcessorItemAsJsonNode = Utils.getSimpleObjectMapper().convertValue(this, JsonNode.class);
public JsonNode toJsonNode() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return this.changeFeedProcessorItemAsJsonNode; }
class ChangeFeedProcessorItem { private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); @JsonProperty("current") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode current; @JsonProperty("previous") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode previous; @JsonProperty("metadata") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode changeFeedMetaData; private ChangeFeedMetaData changeFeedMetaDataInternal; private JsonNode changeFeedProcessorItemAsJsonNode; /** * Constructor * */ public ChangeFeedProcessorItem() {} ChangeFeedProcessorItem(JsonNode changeFeedProcessorItemAsJsonNode) { this.current = changeFeedProcessorItemAsJsonNode.get("current"); this.previous = changeFeedProcessorItemAsJsonNode.get("previous"); this.changeFeedMetaData = changeFeedProcessorItemAsJsonNode.get("metadata"); } /** * Gets the change feed current item. * * @return change feed current item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getCurrent() { return current; } /** * Gets the change feed previous item. * For delete operations, previous image is always going to be provided. * The previous image on replace operations is not going to be exposed by default and requires account-level or container-level opt-in. * * @return change feed previous item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getPrevious() { return previous; } /** * Gets the change feed metadata. * * @return change feed metadata. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @JsonIgnore public ChangeFeedMetaData getChangeFeedMetaData() { if (changeFeedMetaDataInternal == null) { changeFeedMetaDataInternal = new ChangeFeedMetaData(this.changeFeedMetaData); } return changeFeedMetaDataInternal; } /** * Helper API to convert this changeFeedProcessorItem instance to raw JsonNode format. * * @return jsonNode format of this changeFeedProcessorItem instance. * * @throws IllegalArgumentException If conversion fails due to incompatible type; * if so, root cause will contain underlying checked exception data binding functionality threw */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @Override public String toString() { try { return Utils.getSimpleObjectMapper().writeValueAsString(this); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert object to string", e); } } }
class ChangeFeedProcessorItem { @JsonProperty("current") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode current; @JsonProperty("previous") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode previous; @JsonProperty("metadata") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode changeFeedMetaData; private ChangeFeedMetaData changeFeedMetaDataInternal; private JsonNode changeFeedProcessorItemAsJsonNode; /** * Gets the change feed current item. * * @return change feed current item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getCurrent() { return current; } /** * Gets the change feed previous item. * For delete operations, previous image is always going to be provided. * The previous image on replace operations is not going to be exposed by default and requires account-level or container-level opt-in. * * @return change feed previous item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getPrevious() { return previous; } /** * Gets the change feed metadata. * * @return change feed metadata. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @JsonIgnore public ChangeFeedMetaData getChangeFeedMetaData() { if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class); } return this.changeFeedMetaDataInternal; } /** * Helper API to convert this changeFeedProcessorItem instance to raw JsonNode format. * * @return jsonNode format of this changeFeedProcessorItem instance. * * @throws IllegalArgumentException If conversion fails due to incompatible type; * if so, root cause will contain underlying checked exception data binding functionality threw */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @Override public String toString() { try { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return Utils.getSimpleObjectMapper().writeValueAsString(this.changeFeedProcessorItemAsJsonNode); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert object to string", e); } } private JsonNode constructChangeFeedProcessorItemAsJsonNode() { ObjectNode objectNode = Utils.getSimpleObjectMapper().createObjectNode(); if (this.previous != null) { objectNode.set("previous", this.previous); } if (this.current != null) { objectNode.set("current", this.current); } if (this.changeFeedMetaData != null) { objectNode.set("metadata", this.changeFeedMetaData); } return objectNode; } }
I think we can skip this call as part of `toJsonNode()` and only keep it for the getter.
public JsonNode toJsonNode() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class); } return this.changeFeedProcessorItemAsJsonNode; }
if (this.changeFeedMetaDataInternal == null) {
public JsonNode toJsonNode() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return this.changeFeedProcessorItemAsJsonNode; }
class ChangeFeedProcessorItem { @JsonProperty("current") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode current; @JsonProperty("previous") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode previous; @JsonProperty("metadata") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode changeFeedMetaData; private ChangeFeedMetaData changeFeedMetaDataInternal; private JsonNode changeFeedProcessorItemAsJsonNode; /** * Gets the change feed current item. * * @return change feed current item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getCurrent() { return current; } /** * Gets the change feed previous item. * For delete operations, previous image is always going to be provided. * The previous image on replace operations is not going to be exposed by default and requires account-level or container-level opt-in. * * @return change feed previous item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getPrevious() { return previous; } /** * Gets the change feed metadata. * * @return change feed metadata. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @JsonIgnore public ChangeFeedMetaData getChangeFeedMetaData() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class); } return this.changeFeedMetaDataInternal; } /** * Helper API to convert this changeFeedProcessorItem instance to raw JsonNode format. * * @return jsonNode format of this changeFeedProcessorItem instance. * * @throws IllegalArgumentException If conversion fails due to incompatible type; * if so, root cause will contain underlying checked exception data binding functionality threw */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @Override public String toString() { try { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return Utils.getSimpleObjectMapper().writeValueAsString(this.changeFeedProcessorItemAsJsonNode); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert object to string", e); } } private JsonNode constructChangeFeedProcessorItemAsJsonNode() { ObjectNode objectNode = Utils.getSimpleObjectMapper().createObjectNode(); if (this.previous != null) { objectNode.set("previous", this.previous); } if (this.current != null) { objectNode.set("current", this.current); } if (this.changeFeedMetaData != null) { objectNode.set("metadata", this.changeFeedMetaData); } return objectNode; } }
class ChangeFeedProcessorItem { @JsonProperty("current") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode current; @JsonProperty("previous") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode previous; @JsonProperty("metadata") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode changeFeedMetaData; private ChangeFeedMetaData changeFeedMetaDataInternal; private JsonNode changeFeedProcessorItemAsJsonNode; /** * Gets the change feed current item. * * @return change feed current item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getCurrent() { return current; } /** * Gets the change feed previous item. * For delete operations, previous image is always going to be provided. * The previous image on replace operations is not going to be exposed by default and requires account-level or container-level opt-in. * * @return change feed previous item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getPrevious() { return previous; } /** * Gets the change feed metadata. * * @return change feed metadata. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @JsonIgnore public ChangeFeedMetaData getChangeFeedMetaData() { if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class); } return this.changeFeedMetaDataInternal; } /** * Helper API to convert this changeFeedProcessorItem instance to raw JsonNode format. * * @return jsonNode format of this changeFeedProcessorItem instance. * * @throws IllegalArgumentException If conversion fails due to incompatible type; * if so, root cause will contain underlying checked exception data binding functionality threw */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @Override public String toString() { try { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return Utils.getSimpleObjectMapper().writeValueAsString(this.changeFeedProcessorItemAsJsonNode); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert object to string", e); } } private JsonNode constructChangeFeedProcessorItemAsJsonNode() { ObjectNode objectNode = Utils.getSimpleObjectMapper().createObjectNode(); if (this.previous != null) { objectNode.set("previous", this.previous); } if (this.current != null) { objectNode.set("current", this.current); } if (this.changeFeedMetaData != null) { objectNode.set("metadata", this.changeFeedMetaData); } return objectNode; } }
why we need to construct changeFeedProcessorItemAsJsonNode? does not seem to be used in this method
public ChangeFeedMetaData getChangeFeedMetaData() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class); } return this.changeFeedMetaDataInternal; }
if (this.changeFeedProcessorItemAsJsonNode == null) {
public ChangeFeedMetaData getChangeFeedMetaData() { if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class); } return this.changeFeedMetaDataInternal; }
class ChangeFeedProcessorItem { @JsonProperty("current") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode current; @JsonProperty("previous") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode previous; @JsonProperty("metadata") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode changeFeedMetaData; private ChangeFeedMetaData changeFeedMetaDataInternal; private JsonNode changeFeedProcessorItemAsJsonNode; /** * Gets the change feed current item. * * @return change feed current item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getCurrent() { return current; } /** * Gets the change feed previous item. * For delete operations, previous image is always going to be provided. * The previous image on replace operations is not going to be exposed by default and requires account-level or container-level opt-in. * * @return change feed previous item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getPrevious() { return previous; } /** * Gets the change feed metadata. * * @return change feed metadata. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @JsonIgnore /** * Helper API to convert this changeFeedProcessorItem instance to raw JsonNode format. * * @return jsonNode format of this changeFeedProcessorItem instance. * * @throws IllegalArgumentException If conversion fails due to incompatible type; * if so, root cause will contain underlying checked exception data binding functionality threw */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode toJsonNode() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return this.changeFeedProcessorItemAsJsonNode; } @Override public String toString() { try { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return Utils.getSimpleObjectMapper().writeValueAsString(this.changeFeedProcessorItemAsJsonNode); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert object to string", e); } } private JsonNode constructChangeFeedProcessorItemAsJsonNode() { ObjectNode objectNode = Utils.getSimpleObjectMapper().createObjectNode(); if (this.previous != null) { objectNode.set("previous", this.previous); } if (this.current != null) { objectNode.set("current", this.current); } if (this.changeFeedMetaData != null) { objectNode.set("metadata", this.changeFeedMetaData); } return objectNode; } }
class ChangeFeedProcessorItem { @JsonProperty("current") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode current; @JsonProperty("previous") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode previous; @JsonProperty("metadata") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode changeFeedMetaData; private ChangeFeedMetaData changeFeedMetaDataInternal; private JsonNode changeFeedProcessorItemAsJsonNode; /** * Gets the change feed current item. * * @return change feed current item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getCurrent() { return current; } /** * Gets the change feed previous item. * For delete operations, previous image is always going to be provided. * The previous image on replace operations is not going to be exposed by default and requires account-level or container-level opt-in. * * @return change feed previous item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getPrevious() { return previous; } /** * Gets the change feed metadata. * * @return change feed metadata. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @JsonIgnore /** * Helper API to convert this changeFeedProcessorItem instance to raw JsonNode format. * * @return jsonNode format of this changeFeedProcessorItem instance. * * @throws IllegalArgumentException If conversion fails due to incompatible type; * if so, root cause will contain underlying checked exception data binding functionality threw */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode toJsonNode() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return this.changeFeedProcessorItemAsJsonNode; } @Override public String toString() { try { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return Utils.getSimpleObjectMapper().writeValueAsString(this.changeFeedProcessorItemAsJsonNode); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert object to string", e); } } private JsonNode constructChangeFeedProcessorItemAsJsonNode() { ObjectNode objectNode = Utils.getSimpleObjectMapper().createObjectNode(); if (this.previous != null) { objectNode.set("previous", this.previous); } if (this.current != null) { objectNode.set("current", this.current); } if (this.changeFeedMetaData != null) { objectNode.set("metadata", this.changeFeedMetaData); } return objectNode; } }
I don't think we have released the new version of Core Test that does this. Should I make the libraries use it even if it's using the current version from source?
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( MapsRenderClientBuilder.RENDER_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER)));
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode() || interceptorManager.isPlaybackMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( MapsRenderClientBuilder.RENDER_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
class MapsRenderClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } MapsRenderClientBuilder getRenderAsyncClientBuilder(HttpClient httpClient, MapsRenderServiceVersion serviceVersion) { MapsRenderClientBuilder builder = new MapsRenderClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetMapTile(byte[] actual) { assertNotNull(actual); assertTrue(actual.length > 0); } static void validateGetMapTileWithResponse(int expectedStatusCode, Response<BinaryData> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapTile(response.getValue().toBytes()); } static void validateGetMapTileset(MapTileset expected, MapTileset actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getMinZoom(), actual.getMinZoom()); } static void validateGetMapTilesetWithResponse(MapTileset expected, int expectedStatusCode, Response<MapTileset> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapTileset(expected, response.getValue()); } static void validateGetMapAttribution(MapAttribution expected, MapAttribution actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCopyrights().size(), actual.getCopyrights().size()); } static void validateGetMapAttributionWithResponse(MapAttribution expected, int expectedStatusCode, Response<MapAttribution> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapAttribution(expected, response.getValue()); } static void validateGetCopyrightCaption(CopyrightCaption expected, CopyrightCaption actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); } static void validateGetCopyrightCaptionWithResponse(CopyrightCaption expected, int expectedStatusCode, Response<CopyrightCaption> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightCaption(expected, response.getValue()); } static void validateGetCopyrightCaptionFromBoundingBox(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); assertEquals(expected.getRegions().size(), actual.getRegions().size()); } static void validateGetCopyrightCaptionFromBoundingBoxWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightCaptionFromBoundingBox(expected, response.getValue()); } static void validateGetMapStaticImage(byte[] actual) { assertNotNull(actual); assertTrue(actual.length > 0); } static void validateGetMapStaticImageWithResponse(int expectedStatusCode, Response<BinaryData> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapStaticImage(response.getValue().toBytes()); } static void validateGetCopyrightForTile(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); assertEquals(expected.getRegions().size(), actual.getRegions().size()); } static void validateGetCopyrightForTileWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightForTile(expected, response.getValue()); } static void validateGetCopyrightForWorld(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); } static void validateGetCopyrightForWorldWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightForWorld(expected, response.getValue()); } }
class MapsRenderClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } MapsRenderClientBuilder getRenderAsyncClientBuilder(HttpClient httpClient, MapsRenderServiceVersion serviceVersion) { MapsRenderClientBuilder builder = new MapsRenderClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetMapTile(byte[] actual) { assertNotNull(actual); assertTrue(actual.length > 0); } static void validateGetMapTileWithResponse(int expectedStatusCode, Response<BinaryData> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapTile(response.getValue().toBytes()); } static void validateGetMapTileset(MapTileset expected, MapTileset actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getMinZoom(), actual.getMinZoom()); } static void validateGetMapTilesetWithResponse(MapTileset expected, int expectedStatusCode, Response<MapTileset> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapTileset(expected, response.getValue()); } static void validateGetMapAttribution(MapAttribution expected, MapAttribution actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCopyrights().size(), actual.getCopyrights().size()); } static void validateGetMapAttributionWithResponse(MapAttribution expected, int expectedStatusCode, Response<MapAttribution> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapAttribution(expected, response.getValue()); } static void validateGetCopyrightCaption(CopyrightCaption expected, CopyrightCaption actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); } static void validateGetCopyrightCaptionWithResponse(CopyrightCaption expected, int expectedStatusCode, Response<CopyrightCaption> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightCaption(expected, response.getValue()); } static void validateGetCopyrightCaptionFromBoundingBox(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); assertEquals(expected.getRegions().size(), actual.getRegions().size()); } static void validateGetCopyrightCaptionFromBoundingBoxWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightCaptionFromBoundingBox(expected, response.getValue()); } static void validateGetMapStaticImage(byte[] actual) { assertNotNull(actual); assertTrue(actual.length > 0); } static void validateGetMapStaticImageWithResponse(int expectedStatusCode, Response<BinaryData> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapStaticImage(response.getValue().toBytes()); } static void validateGetCopyrightForTile(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); assertEquals(expected.getRegions().size(), actual.getRegions().size()); } static void validateGetCopyrightForTileWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightForTile(expected, response.getValue()); } static void validateGetCopyrightForWorld(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); } static void validateGetCopyrightForWorldWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightForWorld(expected, response.getValue()); } }
do we need to validate changeFeedMetaData is not null?
public ChangeFeedMetaData getChangeFeedMetaData() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class); } return this.changeFeedMetaDataInternal; }
this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class);
public ChangeFeedMetaData getChangeFeedMetaData() { if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class); } return this.changeFeedMetaDataInternal; }
class ChangeFeedProcessorItem { @JsonProperty("current") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode current; @JsonProperty("previous") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode previous; @JsonProperty("metadata") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode changeFeedMetaData; private ChangeFeedMetaData changeFeedMetaDataInternal; private JsonNode changeFeedProcessorItemAsJsonNode; /** * Gets the change feed current item. * * @return change feed current item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getCurrent() { return current; } /** * Gets the change feed previous item. * For delete operations, previous image is always going to be provided. * The previous image on replace operations is not going to be exposed by default and requires account-level or container-level opt-in. * * @return change feed previous item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getPrevious() { return previous; } /** * Gets the change feed metadata. * * @return change feed metadata. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @JsonIgnore /** * Helper API to convert this changeFeedProcessorItem instance to raw JsonNode format. * * @return jsonNode format of this changeFeedProcessorItem instance. * * @throws IllegalArgumentException If conversion fails due to incompatible type; * if so, root cause will contain underlying checked exception data binding functionality threw */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode toJsonNode() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return this.changeFeedProcessorItemAsJsonNode; } @Override public String toString() { try { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return Utils.getSimpleObjectMapper().writeValueAsString(this.changeFeedProcessorItemAsJsonNode); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert object to string", e); } } private JsonNode constructChangeFeedProcessorItemAsJsonNode() { ObjectNode objectNode = Utils.getSimpleObjectMapper().createObjectNode(); if (this.previous != null) { objectNode.set("previous", this.previous); } if (this.current != null) { objectNode.set("current", this.current); } if (this.changeFeedMetaData != null) { objectNode.set("metadata", this.changeFeedMetaData); } return objectNode; } }
class ChangeFeedProcessorItem { @JsonProperty("current") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode current; @JsonProperty("previous") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode previous; @JsonProperty("metadata") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode changeFeedMetaData; private ChangeFeedMetaData changeFeedMetaDataInternal; private JsonNode changeFeedProcessorItemAsJsonNode; /** * Gets the change feed current item. * * @return change feed current item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getCurrent() { return current; } /** * Gets the change feed previous item. * For delete operations, previous image is always going to be provided. * The previous image on replace operations is not going to be exposed by default and requires account-level or container-level opt-in. * * @return change feed previous item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getPrevious() { return previous; } /** * Gets the change feed metadata. * * @return change feed metadata. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @JsonIgnore /** * Helper API to convert this changeFeedProcessorItem instance to raw JsonNode format. * * @return jsonNode format of this changeFeedProcessorItem instance. * * @throws IllegalArgumentException If conversion fails due to incompatible type; * if so, root cause will contain underlying checked exception data binding functionality threw */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode toJsonNode() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return this.changeFeedProcessorItemAsJsonNode; } @Override public String toString() { try { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return Utils.getSimpleObjectMapper().writeValueAsString(this.changeFeedProcessorItemAsJsonNode); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert object to string", e); } } private JsonNode constructChangeFeedProcessorItemAsJsonNode() { ObjectNode objectNode = Utils.getSimpleObjectMapper().createObjectNode(); if (this.previous != null) { objectNode.set("previous", this.previous); } if (this.current != null) { objectNode.set("current", this.current); } if (this.changeFeedMetaData != null) { objectNode.set("metadata", this.changeFeedMetaData); } return objectNode; } }
`convertValue()` will return `null` with no exceptions. So, no additional check needed.
public ChangeFeedMetaData getChangeFeedMetaData() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class); } return this.changeFeedMetaDataInternal; }
this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class);
public ChangeFeedMetaData getChangeFeedMetaData() { if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class); } return this.changeFeedMetaDataInternal; }
class ChangeFeedProcessorItem { @JsonProperty("current") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode current; @JsonProperty("previous") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode previous; @JsonProperty("metadata") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode changeFeedMetaData; private ChangeFeedMetaData changeFeedMetaDataInternal; private JsonNode changeFeedProcessorItemAsJsonNode; /** * Gets the change feed current item. * * @return change feed current item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getCurrent() { return current; } /** * Gets the change feed previous item. * For delete operations, previous image is always going to be provided. * The previous image on replace operations is not going to be exposed by default and requires account-level or container-level opt-in. * * @return change feed previous item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getPrevious() { return previous; } /** * Gets the change feed metadata. * * @return change feed metadata. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @JsonIgnore /** * Helper API to convert this changeFeedProcessorItem instance to raw JsonNode format. * * @return jsonNode format of this changeFeedProcessorItem instance. * * @throws IllegalArgumentException If conversion fails due to incompatible type; * if so, root cause will contain underlying checked exception data binding functionality threw */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode toJsonNode() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return this.changeFeedProcessorItemAsJsonNode; } @Override public String toString() { try { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return Utils.getSimpleObjectMapper().writeValueAsString(this.changeFeedProcessorItemAsJsonNode); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert object to string", e); } } private JsonNode constructChangeFeedProcessorItemAsJsonNode() { ObjectNode objectNode = Utils.getSimpleObjectMapper().createObjectNode(); if (this.previous != null) { objectNode.set("previous", this.previous); } if (this.current != null) { objectNode.set("current", this.current); } if (this.changeFeedMetaData != null) { objectNode.set("metadata", this.changeFeedMetaData); } return objectNode; } }
class ChangeFeedProcessorItem { @JsonProperty("current") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode current; @JsonProperty("previous") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode previous; @JsonProperty("metadata") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode changeFeedMetaData; private ChangeFeedMetaData changeFeedMetaDataInternal; private JsonNode changeFeedProcessorItemAsJsonNode; /** * Gets the change feed current item. * * @return change feed current item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getCurrent() { return current; } /** * Gets the change feed previous item. * For delete operations, previous image is always going to be provided. * The previous image on replace operations is not going to be exposed by default and requires account-level or container-level opt-in. * * @return change feed previous item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getPrevious() { return previous; } /** * Gets the change feed metadata. * * @return change feed metadata. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @JsonIgnore /** * Helper API to convert this changeFeedProcessorItem instance to raw JsonNode format. * * @return jsonNode format of this changeFeedProcessorItem instance. * * @throws IllegalArgumentException If conversion fails due to incompatible type; * if so, root cause will contain underlying checked exception data binding functionality threw */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode toJsonNode() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return this.changeFeedProcessorItemAsJsonNode; } @Override public String toString() { try { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return Utils.getSimpleObjectMapper().writeValueAsString(this.changeFeedProcessorItemAsJsonNode); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert object to string", e); } } private JsonNode constructChangeFeedProcessorItemAsJsonNode() { ObjectNode objectNode = Utils.getSimpleObjectMapper().createObjectNode(); if (this.previous != null) { objectNode.set("previous", this.previous); } if (this.current != null) { objectNode.set("current", this.current); } if (this.changeFeedMetaData != null) { objectNode.set("metadata", this.changeFeedMetaData); } return objectNode; } }
Fixed in next iteration.
public JsonNode toJsonNode() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class); } return this.changeFeedProcessorItemAsJsonNode; }
if (this.changeFeedMetaDataInternal == null) {
public JsonNode toJsonNode() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return this.changeFeedProcessorItemAsJsonNode; }
class ChangeFeedProcessorItem { @JsonProperty("current") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode current; @JsonProperty("previous") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode previous; @JsonProperty("metadata") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode changeFeedMetaData; private ChangeFeedMetaData changeFeedMetaDataInternal; private JsonNode changeFeedProcessorItemAsJsonNode; /** * Gets the change feed current item. * * @return change feed current item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getCurrent() { return current; } /** * Gets the change feed previous item. * For delete operations, previous image is always going to be provided. * The previous image on replace operations is not going to be exposed by default and requires account-level or container-level opt-in. * * @return change feed previous item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getPrevious() { return previous; } /** * Gets the change feed metadata. * * @return change feed metadata. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @JsonIgnore public ChangeFeedMetaData getChangeFeedMetaData() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class); } return this.changeFeedMetaDataInternal; } /** * Helper API to convert this changeFeedProcessorItem instance to raw JsonNode format. * * @return jsonNode format of this changeFeedProcessorItem instance. * * @throws IllegalArgumentException If conversion fails due to incompatible type; * if so, root cause will contain underlying checked exception data binding functionality threw */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @Override public String toString() { try { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return Utils.getSimpleObjectMapper().writeValueAsString(this.changeFeedProcessorItemAsJsonNode); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert object to string", e); } } private JsonNode constructChangeFeedProcessorItemAsJsonNode() { ObjectNode objectNode = Utils.getSimpleObjectMapper().createObjectNode(); if (this.previous != null) { objectNode.set("previous", this.previous); } if (this.current != null) { objectNode.set("current", this.current); } if (this.changeFeedMetaData != null) { objectNode.set("metadata", this.changeFeedMetaData); } return objectNode; } }
class ChangeFeedProcessorItem { @JsonProperty("current") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode current; @JsonProperty("previous") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode previous; @JsonProperty("metadata") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode changeFeedMetaData; private ChangeFeedMetaData changeFeedMetaDataInternal; private JsonNode changeFeedProcessorItemAsJsonNode; /** * Gets the change feed current item. * * @return change feed current item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getCurrent() { return current; } /** * Gets the change feed previous item. * For delete operations, previous image is always going to be provided. * The previous image on replace operations is not going to be exposed by default and requires account-level or container-level opt-in. * * @return change feed previous item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getPrevious() { return previous; } /** * Gets the change feed metadata. * * @return change feed metadata. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @JsonIgnore public ChangeFeedMetaData getChangeFeedMetaData() { if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class); } return this.changeFeedMetaDataInternal; } /** * Helper API to convert this changeFeedProcessorItem instance to raw JsonNode format. * * @return jsonNode format of this changeFeedProcessorItem instance. * * @throws IllegalArgumentException If conversion fails due to incompatible type; * if so, root cause will contain underlying checked exception data binding functionality threw */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @Override public String toString() { try { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return Utils.getSimpleObjectMapper().writeValueAsString(this.changeFeedProcessorItemAsJsonNode); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert object to string", e); } } private JsonNode constructChangeFeedProcessorItemAsJsonNode() { ObjectNode objectNode = Utils.getSimpleObjectMapper().createObjectNode(); if (this.previous != null) { objectNode.set("previous", this.previous); } if (this.current != null) { objectNode.set("current", this.current); } if (this.changeFeedMetaData != null) { objectNode.set("metadata", this.changeFeedMetaData); } return objectNode; } }
Fixed in next iteration.
public ChangeFeedMetaData getChangeFeedMetaData() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class); } return this.changeFeedMetaDataInternal; }
if (this.changeFeedProcessorItemAsJsonNode == null) {
public ChangeFeedMetaData getChangeFeedMetaData() { if (this.changeFeedMetaDataInternal == null) { this.changeFeedMetaDataInternal = Utils.getSimpleObjectMapper().convertValue(this.changeFeedMetaData, ChangeFeedMetaData.class); } return this.changeFeedMetaDataInternal; }
class ChangeFeedProcessorItem { @JsonProperty("current") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode current; @JsonProperty("previous") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode previous; @JsonProperty("metadata") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode changeFeedMetaData; private ChangeFeedMetaData changeFeedMetaDataInternal; private JsonNode changeFeedProcessorItemAsJsonNode; /** * Gets the change feed current item. * * @return change feed current item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getCurrent() { return current; } /** * Gets the change feed previous item. * For delete operations, previous image is always going to be provided. * The previous image on replace operations is not going to be exposed by default and requires account-level or container-level opt-in. * * @return change feed previous item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getPrevious() { return previous; } /** * Gets the change feed metadata. * * @return change feed metadata. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @JsonIgnore /** * Helper API to convert this changeFeedProcessorItem instance to raw JsonNode format. * * @return jsonNode format of this changeFeedProcessorItem instance. * * @throws IllegalArgumentException If conversion fails due to incompatible type; * if so, root cause will contain underlying checked exception data binding functionality threw */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode toJsonNode() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return this.changeFeedProcessorItemAsJsonNode; } @Override public String toString() { try { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return Utils.getSimpleObjectMapper().writeValueAsString(this.changeFeedProcessorItemAsJsonNode); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert object to string", e); } } private JsonNode constructChangeFeedProcessorItemAsJsonNode() { ObjectNode objectNode = Utils.getSimpleObjectMapper().createObjectNode(); if (this.previous != null) { objectNode.set("previous", this.previous); } if (this.current != null) { objectNode.set("current", this.current); } if (this.changeFeedMetaData != null) { objectNode.set("metadata", this.changeFeedMetaData); } return objectNode; } }
class ChangeFeedProcessorItem { @JsonProperty("current") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode current; @JsonProperty("previous") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode previous; @JsonProperty("metadata") @JsonInclude(JsonInclude.Include.NON_NULL) private JsonNode changeFeedMetaData; private ChangeFeedMetaData changeFeedMetaDataInternal; private JsonNode changeFeedProcessorItemAsJsonNode; /** * Gets the change feed current item. * * @return change feed current item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getCurrent() { return current; } /** * Gets the change feed previous item. * For delete operations, previous image is always going to be provided. * The previous image on replace operations is not going to be exposed by default and requires account-level or container-level opt-in. * * @return change feed previous item. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode getPrevious() { return previous; } /** * Gets the change feed metadata. * * @return change feed metadata. */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) @JsonIgnore /** * Helper API to convert this changeFeedProcessorItem instance to raw JsonNode format. * * @return jsonNode format of this changeFeedProcessorItem instance. * * @throws IllegalArgumentException If conversion fails due to incompatible type; * if so, root cause will contain underlying checked exception data binding functionality threw */ @Beta(value = Beta.SinceVersion.V4_37_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public JsonNode toJsonNode() { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return this.changeFeedProcessorItemAsJsonNode; } @Override public String toString() { try { if (this.changeFeedProcessorItemAsJsonNode == null) { this.changeFeedProcessorItemAsJsonNode = constructChangeFeedProcessorItemAsJsonNode(); } return Utils.getSimpleObjectMapper().writeValueAsString(this.changeFeedProcessorItemAsJsonNode); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert object to string", e); } } private JsonNode constructChangeFeedProcessorItemAsJsonNode() { ObjectNode objectNode = Utils.getSimpleObjectMapper().createObjectNode(); if (this.previous != null) { objectNode.set("previous", this.previous); } if (this.current != null) { objectNode.set("current", this.current); } if (this.changeFeedMetaData != null) { objectNode.set("metadata", this.changeFeedMetaData); } return objectNode; } }
Do you think that we can use ObjectMapper to do case-insensitive deserialization here?
public boolean evaluate(FeatureFilterEvaluationContext context) { if (context == null) { throw new IllegalArgumentException("Targeting Context not configured."); } TargetingFilterContext targetingContext = new TargetingFilterContext(); contextAccessor.configureTargetingContext(targetingContext); if (validateTargetingContext(targetingContext)) { LOGGER.warn("No targeting context available for targeting evaluation."); return false; } Map<String, Object> parameters = context.getParameters(); Object audienceObject = parameters.get(AUDIENCE); if (audienceObject != null) { parameters = (Map<String, Object>) audienceObject; } updateValueFromMapToList(parameters, USERS); updateValueFromMapToList(parameters, GROUPS); Audience audience; Map<String, List<String>> exclusionMap; String exclusionValue = getKeyFormat(parameters, EXCLUSION_CAMEL); String exclusionUserValue = getKeyFormat((Map<String, Object>) parameters.get(exclusionValue), "Users"); String exclusionGroupsValue = getKeyFormat((Map<String, Object>) parameters.get(exclusionValue), "Groups"); if (((Map<String, Object>) parameters.getOrDefault(exclusionValue, new HashMap<>())) .get(exclusionUserValue) instanceof List) { audience = OBJECT_MAPPER.convertValue(parameters, Audience.class); exclusionMap = (Map<String, List<String>>) parameters.get(exclusionValue); } else { exclusionMap = (Map<String, List<String>>) parameters.remove(exclusionValue); audience = OBJECT_MAPPER.convertValue(parameters, Audience.class); parameters.put(exclusionValue, exclusionMap); } if (exclusionMap != null) { Map<String, List<String>> updatedExclusions = new HashMap<>(); Object users = exclusionMap.get(exclusionUserValue); Object groups = exclusionMap.get(exclusionGroupsValue); if (users instanceof Map) { users = new ArrayList<>(((Map<String, String>) users).values()); } if (groups instanceof Map) { groups = new ArrayList<>(((Map<String, String>) groups).values()); } updatedExclusions.put(USERS, (List<String>) users); updatedExclusions.put(GROUPS, (List<String>) groups); Exclusion exclusion = OBJECT_MAPPER.convertValue(updatedExclusions, Exclusion.class); audience.setExclusion(exclusion); } else if (audience.getExclusion() == null) { audience.setExclusion(new Exclusion()); } validateSettings(audience); if (targetUser(targetingContext.getUserId(), audience.getExclusion().getUsers())) { return false; } if (targetingContext.getGroups() != null && audience.getExclusion().getGroups() != null) { for (String group : targetingContext.getGroups()) { Optional<String> groupRollout = audience.getExclusion().getGroups().stream() .filter(g -> equals(g, group)).findFirst(); if (groupRollout.isPresent()) { return false; } } } if (targetUser(targetingContext.getUserId(), audience.getUsers())) { return true; } if (targetingContext.getGroups() != null && audience.getGroups() != null) { for (String group : targetingContext.getGroups()) { if (targetGroup(audience, targetingContext, context, group)) { return true; } } } String defaultContextId = targetingContext.getUserId() + "\n" + context.getFeatureName(); return isTargeted(defaultContextId, audience.getDefaultRolloutPercentage()); }
Audience audience;
public boolean evaluate(FeatureFilterEvaluationContext context) { if (context == null) { throw new IllegalArgumentException("Targeting Context not configured."); } TargetingFilterContext targetingContext = new TargetingFilterContext(); contextAccessor.configureTargetingContext(targetingContext); if (validateTargetingContext(targetingContext)) { LOGGER.warn("No targeting context available for targeting evaluation."); return false; } Map<String, Object> parameters = context.getParameters(); Object audienceObject = parameters.get(AUDIENCE); if (audienceObject != null) { parameters = (Map<String, Object>) audienceObject; } updateValueFromMapToList(parameters, USERS); updateValueFromMapToList(parameters, GROUPS); Audience audience; String exclusionValue = getKeyCase(parameters, EXCLUSION_CAMEL); String exclusionUserValue = getKeyCase((Map<String, Object>) parameters.get(exclusionValue), "Users"); String exclusionGroupsValue = getKeyCase((Map<String, Object>) parameters.get(exclusionValue), "Groups"); if (((Map<String, Object>) parameters.getOrDefault(exclusionValue, new HashMap<>())) .get(exclusionUserValue) instanceof List) { audience = OBJECT_MAPPER.convertValue(parameters, Audience.class); } else { Map<String, List<String>> exclusionMap = (Map<String, List<String>>) parameters.remove(exclusionValue); if (exclusionMap == null) { exclusionMap = new HashMap<>(); } audience = OBJECT_MAPPER.convertValue(parameters, Audience.class); Exclusion exclusion = new Exclusion(); Object users = exclusionMap.get(exclusionUserValue); Object groups = exclusionMap.get(exclusionGroupsValue); if (users instanceof Map) { exclusion.setUsers(new ArrayList<>(((Map<String, String>) users).values())); } if (groups instanceof Map) { exclusion.setGroups(new ArrayList<>(((Map<String, String>) groups).values())); } audience.setExclusion(exclusion); } validateSettings(audience); if (targetUser(targetingContext.getUserId(), audience.getExclusion().getUsers())) { return false; } if (targetingContext.getGroups() != null && audience.getExclusion().getGroups() != null) { for (String group : targetingContext.getGroups()) { Optional<String> groupRollout = audience.getExclusion().getGroups().stream() .filter(g -> equals(g, group)).findFirst(); if (groupRollout.isPresent()) { return false; } } } if (targetUser(targetingContext.getUserId(), audience.getUsers())) { return true; } if (targetingContext.getGroups() != null && audience.getGroups() != null) { for (String group : targetingContext.getGroups()) { if (targetGroup(audience, targetingContext, context, group)) { return true; } } } String defaultContextId = targetingContext.getUserId() + "\n" + context.getFeatureName(); return isTargeted(defaultContextId, audience.getDefaultRolloutPercentage()); }
class TargetingFilter implements FeatureFilter { private static final Logger LOGGER = LoggerFactory.getLogger(TargetingFilter.class); /** * users field in the filter */ protected static final String USERS = "users"; /** * groups field in the filter */ protected static final String GROUPS = "groups"; /** * Audience in the filter */ protected static final String AUDIENCE = "Audience"; /** * Audience that always returns false */ protected static final String EXCLUSION = "exclusion"; private static final String EXCLUSION_CAMEL = "Exclusion"; /** * Error message for when the total Audience value is greater than 100 percent. */ protected static final String OUT_OF_RANGE = "The value is out of the accepted range."; private static final String REQUIRED_PARAMETER = "Value cannot be null."; /** * Object Mapper for converting configurations to features */ protected static final ObjectMapper OBJECT_MAPPER = JsonMapper.builder() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true).build(); /** * Accessor for identifying the current user/group when evaluating */ protected final TargetingContextAccessor contextAccessor; /** * Options for evaluating the filter */ protected final TargetingEvaluationOptions options; /** * Filter for targeting a user/group/percentage of users. * * @param contextAccessor Accessor for identifying the current user/group when evaluating */ public TargetingFilter(TargetingContextAccessor contextAccessor) { this.contextAccessor = contextAccessor; this.options = new TargetingEvaluationOptions(); } /** * `Microsoft.TargetingFilter` evaluates a user/group/overall rollout of a feature. * * @param contextAccessor Context for evaluating the users/groups. * @param options enables customization of the filter. */ public TargetingFilter(TargetingContextAccessor contextAccessor, TargetingEvaluationOptions options) { this.contextAccessor = contextAccessor; this.options = options; } @Override @SuppressWarnings("unchecked") private String getKeyFormat(Map<String, Object> parameters, String key) { if (parameters != null && parameters.containsKey(key)) { return key; } return key.toLowerCase(Locale.getDefault()); } private boolean targetUser(String userId, List<String> users) { return userId != null && users != null && users.stream().anyMatch(user -> equals(userId, user)); } private boolean targetGroup(Audience audience, TargetingFilterContext targetingContext, FeatureFilterEvaluationContext context, String group) { Optional<GroupRollout> groupRollout = audience.getGroups().stream() .filter(g -> equals(g.getName(), group)).findFirst(); if (groupRollout.isPresent()) { String audienceContextId = targetingContext.getUserId() + "\n" + context.getName() + "\n" + group; if (isTargeted(audienceContextId, groupRollout.get().getRolloutPercentage())) { return true; } } return false; } private boolean validateTargetingContext(TargetingFilterContext targetingContext) { boolean hasUserDefined = StringUtils.hasText(targetingContext.getUserId()); boolean hasGroupsDefined = targetingContext.getGroups() != null; boolean hasAtLeastOneGroup = false; if (hasGroupsDefined) { hasAtLeastOneGroup = targetingContext.getGroups().stream().anyMatch(group -> StringUtils.hasText(group)); } return (!hasUserDefined && !(hasGroupsDefined && hasAtLeastOneGroup)); } /** * Computes the percentage that the contextId falls into. * * @param contextId Id of the context being targeted * @return the bucket value of the context id * @throws TargetingException Unable to create hash of target context */ protected double isTargetedPercentage(String contextId) { byte[] hash = null; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); hash = digest.digest(contextId.getBytes(Charset.defaultCharset())); } catch (NoSuchAlgorithmException e) { throw new TargetingException("Unable to find SHA-256 for targeting.", e); } if (hash == null) { throw new TargetingException("Unable to create Targeting Hash for " + contextId); } ByteBuffer wrapped = ByteBuffer.wrap(hash); int contextMarker = Math.abs(wrapped.getInt()); return (contextMarker / (double) Integer.MAX_VALUE) * 100; } private boolean isTargeted(String contextId, double percentage) { return isTargetedPercentage(contextId) < percentage; } /** * Validates the settings of a targeting filter. * * @param settings targeting filter settings * @throws TargetingException when a required parameter is missing or percentage value is greater than 100. */ void validateSettings(Audience audience) { String paramName = ""; String reason = ""; if (audience == null) { paramName = AUDIENCE; reason = REQUIRED_PARAMETER; throw new TargetingException(paramName + " : " + reason); } if (audience.getDefaultRolloutPercentage() < 0 || audience.getDefaultRolloutPercentage() > 100) { paramName = AUDIENCE + "." + audience.getDefaultRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } List<GroupRollout> groups = audience.getGroups(); if (groups != null) { for (int index = 0; index < groups.size(); index++) { GroupRollout groupRollout = groups.get(index); if (groupRollout.getRolloutPercentage() < 0 || groupRollout.getRolloutPercentage() > 100) { paramName = AUDIENCE + "[" + index + "]." + groups.get(index).getRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } } } } /** * Checks if two strings are equal, ignores case if configured to. * * @param s1 string to compare * @param s2 string to compare * @return true if the strings are equal */ private boolean equals(String s1, String s2) { if (options.isIgnoreCase()) { return s1.equalsIgnoreCase(s2); } return s1.equals(s2); } /** * Looks at the given key in the parameters and coverts it to a list if it is currently a map. Used for updating * fields in the targeting filter. * * @param <T> Type of object inside of parameters for the given key * @param parameters map of generic objects * @param key key of object int the parameters map */ @SuppressWarnings("unchecked") private void updateValueFromMapToList(Map<String, Object> parameters, String key) { Object objectMap = parameters.get(key); if (objectMap instanceof Map) { Collection<Object> toType = ((Map<String, Object>) objectMap).values(); parameters.put(key, toType); } } }
class TargetingFilter implements FeatureFilter { private static final Logger LOGGER = LoggerFactory.getLogger(TargetingFilter.class); /** * users field in the filter */ protected static final String USERS = "users"; /** * groups field in the filter */ protected static final String GROUPS = "groups"; /** * Audience in the filter */ protected static final String AUDIENCE = "Audience"; /** * Audience that always returns false */ protected static final String EXCLUSION = "exclusion"; private static final String EXCLUSION_CAMEL = "Exclusion"; /** * Error message for when the total Audience value is greater than 100 percent. */ protected static final String OUT_OF_RANGE = "The value is out of the accepted range."; private static final String REQUIRED_PARAMETER = "Value cannot be null."; /** * Object Mapper for converting configurations to features */ protected static final ObjectMapper OBJECT_MAPPER = JsonMapper.builder() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true).build(); /** * Accessor for identifying the current user/group when evaluating */ protected final TargetingContextAccessor contextAccessor; /** * Options for evaluating the filter */ protected final TargetingEvaluationOptions options; /** * Filter for targeting a user/group/percentage of users. * * @param contextAccessor Accessor for identifying the current user/group when evaluating */ public TargetingFilter(TargetingContextAccessor contextAccessor) { this.contextAccessor = contextAccessor; this.options = new TargetingEvaluationOptions(); } /** * `Microsoft.TargetingFilter` evaluates a user/group/overall rollout of a feature. * * @param contextAccessor Context for evaluating the users/groups. * @param options enables customization of the filter. */ public TargetingFilter(TargetingContextAccessor contextAccessor, TargetingEvaluationOptions options) { this.contextAccessor = contextAccessor; this.options = options; } @Override @SuppressWarnings("unchecked") private String getKeyCase(Map<String, Object> parameters, String key) { if (parameters != null && parameters.containsKey(key)) { return key; } return key.toLowerCase(Locale.getDefault()); } private boolean targetUser(String userId, List<String> users) { return userId != null && users != null && users.stream().anyMatch(user -> equals(userId, user)); } private boolean targetGroup(Audience audience, TargetingFilterContext targetingContext, FeatureFilterEvaluationContext context, String group) { Optional<GroupRollout> groupRollout = audience.getGroups().stream() .filter(g -> equals(g.getName(), group)).findFirst(); if (groupRollout.isPresent()) { String audienceContextId = targetingContext.getUserId() + "\n" + context.getName() + "\n" + group; if (isTargeted(audienceContextId, groupRollout.get().getRolloutPercentage())) { return true; } } return false; } private boolean validateTargetingContext(TargetingFilterContext targetingContext) { boolean hasUserDefined = StringUtils.hasText(targetingContext.getUserId()); boolean hasGroupsDefined = targetingContext.getGroups() != null; boolean hasAtLeastOneGroup = false; if (hasGroupsDefined) { hasAtLeastOneGroup = targetingContext.getGroups().stream().anyMatch(group -> StringUtils.hasText(group)); } return (!hasUserDefined && !(hasGroupsDefined && hasAtLeastOneGroup)); } /** * Computes the percentage that the contextId falls into. * * @param contextId Id of the context being targeted * @return the bucket value of the context id * @throws TargetingException Unable to create hash of target context */ protected double isTargetedPercentage(String contextId) { byte[] hash = null; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); hash = digest.digest(contextId.getBytes(Charset.defaultCharset())); } catch (NoSuchAlgorithmException e) { throw new TargetingException("Unable to find SHA-256 for targeting.", e); } if (hash == null) { throw new TargetingException("Unable to create Targeting Hash for " + contextId); } ByteBuffer wrapped = ByteBuffer.wrap(hash); int contextMarker = Math.abs(wrapped.getInt()); return (contextMarker / (double) Integer.MAX_VALUE) * 100; } private boolean isTargeted(String contextId, double percentage) { return isTargetedPercentage(contextId) < percentage; } /** * Validates the settings of a targeting filter. * * @param settings targeting filter settings * @throws TargetingException when a required parameter is missing or percentage value is greater than 100. */ void validateSettings(Audience audience) { String paramName = ""; String reason = ""; if (audience == null) { paramName = AUDIENCE; reason = REQUIRED_PARAMETER; throw new TargetingException(paramName + " : " + reason); } if (audience.getDefaultRolloutPercentage() < 0 || audience.getDefaultRolloutPercentage() > 100) { paramName = AUDIENCE + "." + audience.getDefaultRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } List<GroupRollout> groups = audience.getGroups(); if (groups != null) { for (int index = 0; index < groups.size(); index++) { GroupRollout groupRollout = groups.get(index); if (groupRollout.getRolloutPercentage() < 0 || groupRollout.getRolloutPercentage() > 100) { paramName = AUDIENCE + "[" + index + "]." + groups.get(index).getRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } } } } /** * Checks if two strings are equal, ignores case if configured to. * * @param s1 string to compare * @param s2 string to compare * @return true if the strings are equal */ private boolean equals(String s1, String s2) { if (options.isIgnoreCase()) { return s1.equalsIgnoreCase(s2); } return s1.equals(s2); } /** * Looks at the given key in the parameters and coverts it to a list if it is currently a map. Used for updating * fields in the targeting filter. * * @param <T> Type of object inside of parameters for the given key * @param parameters map of generic objects * @param key key of object int the parameters map */ @SuppressWarnings("unchecked") private void updateValueFromMapToList(Map<String, Object> parameters, String key) { Object objectMap = parameters.get(key); if (objectMap instanceof Map) { Collection<Object> toType = ((Map<String, Object>) objectMap).values(); parameters.put(key, toType); } } }
The issue here is that when Spring ingested the configuration it takes all lists and converts them to `Map` with key = location in the list.
public boolean evaluate(FeatureFilterEvaluationContext context) { if (context == null) { throw new IllegalArgumentException("Targeting Context not configured."); } TargetingFilterContext targetingContext = new TargetingFilterContext(); contextAccessor.configureTargetingContext(targetingContext); if (validateTargetingContext(targetingContext)) { LOGGER.warn("No targeting context available for targeting evaluation."); return false; } Map<String, Object> parameters = context.getParameters(); Object audienceObject = parameters.get(AUDIENCE); if (audienceObject != null) { parameters = (Map<String, Object>) audienceObject; } updateValueFromMapToList(parameters, USERS); updateValueFromMapToList(parameters, GROUPS); Audience audience; Map<String, List<String>> exclusionMap; String exclusionValue = getKeyFormat(parameters, EXCLUSION_CAMEL); String exclusionUserValue = getKeyFormat((Map<String, Object>) parameters.get(exclusionValue), "Users"); String exclusionGroupsValue = getKeyFormat((Map<String, Object>) parameters.get(exclusionValue), "Groups"); if (((Map<String, Object>) parameters.getOrDefault(exclusionValue, new HashMap<>())) .get(exclusionUserValue) instanceof List) { audience = OBJECT_MAPPER.convertValue(parameters, Audience.class); exclusionMap = (Map<String, List<String>>) parameters.get(exclusionValue); } else { exclusionMap = (Map<String, List<String>>) parameters.remove(exclusionValue); audience = OBJECT_MAPPER.convertValue(parameters, Audience.class); parameters.put(exclusionValue, exclusionMap); } if (exclusionMap != null) { Map<String, List<String>> updatedExclusions = new HashMap<>(); Object users = exclusionMap.get(exclusionUserValue); Object groups = exclusionMap.get(exclusionGroupsValue); if (users instanceof Map) { users = new ArrayList<>(((Map<String, String>) users).values()); } if (groups instanceof Map) { groups = new ArrayList<>(((Map<String, String>) groups).values()); } updatedExclusions.put(USERS, (List<String>) users); updatedExclusions.put(GROUPS, (List<String>) groups); Exclusion exclusion = OBJECT_MAPPER.convertValue(updatedExclusions, Exclusion.class); audience.setExclusion(exclusion); } else if (audience.getExclusion() == null) { audience.setExclusion(new Exclusion()); } validateSettings(audience); if (targetUser(targetingContext.getUserId(), audience.getExclusion().getUsers())) { return false; } if (targetingContext.getGroups() != null && audience.getExclusion().getGroups() != null) { for (String group : targetingContext.getGroups()) { Optional<String> groupRollout = audience.getExclusion().getGroups().stream() .filter(g -> equals(g, group)).findFirst(); if (groupRollout.isPresent()) { return false; } } } if (targetUser(targetingContext.getUserId(), audience.getUsers())) { return true; } if (targetingContext.getGroups() != null && audience.getGroups() != null) { for (String group : targetingContext.getGroups()) { if (targetGroup(audience, targetingContext, context, group)) { return true; } } } String defaultContextId = targetingContext.getUserId() + "\n" + context.getFeatureName(); return isTargeted(defaultContextId, audience.getDefaultRolloutPercentage()); }
Audience audience;
public boolean evaluate(FeatureFilterEvaluationContext context) { if (context == null) { throw new IllegalArgumentException("Targeting Context not configured."); } TargetingFilterContext targetingContext = new TargetingFilterContext(); contextAccessor.configureTargetingContext(targetingContext); if (validateTargetingContext(targetingContext)) { LOGGER.warn("No targeting context available for targeting evaluation."); return false; } Map<String, Object> parameters = context.getParameters(); Object audienceObject = parameters.get(AUDIENCE); if (audienceObject != null) { parameters = (Map<String, Object>) audienceObject; } updateValueFromMapToList(parameters, USERS); updateValueFromMapToList(parameters, GROUPS); Audience audience; String exclusionValue = getKeyCase(parameters, EXCLUSION_CAMEL); String exclusionUserValue = getKeyCase((Map<String, Object>) parameters.get(exclusionValue), "Users"); String exclusionGroupsValue = getKeyCase((Map<String, Object>) parameters.get(exclusionValue), "Groups"); if (((Map<String, Object>) parameters.getOrDefault(exclusionValue, new HashMap<>())) .get(exclusionUserValue) instanceof List) { audience = OBJECT_MAPPER.convertValue(parameters, Audience.class); } else { Map<String, List<String>> exclusionMap = (Map<String, List<String>>) parameters.remove(exclusionValue); if (exclusionMap == null) { exclusionMap = new HashMap<>(); } audience = OBJECT_MAPPER.convertValue(parameters, Audience.class); Exclusion exclusion = new Exclusion(); Object users = exclusionMap.get(exclusionUserValue); Object groups = exclusionMap.get(exclusionGroupsValue); if (users instanceof Map) { exclusion.setUsers(new ArrayList<>(((Map<String, String>) users).values())); } if (groups instanceof Map) { exclusion.setGroups(new ArrayList<>(((Map<String, String>) groups).values())); } audience.setExclusion(exclusion); } validateSettings(audience); if (targetUser(targetingContext.getUserId(), audience.getExclusion().getUsers())) { return false; } if (targetingContext.getGroups() != null && audience.getExclusion().getGroups() != null) { for (String group : targetingContext.getGroups()) { Optional<String> groupRollout = audience.getExclusion().getGroups().stream() .filter(g -> equals(g, group)).findFirst(); if (groupRollout.isPresent()) { return false; } } } if (targetUser(targetingContext.getUserId(), audience.getUsers())) { return true; } if (targetingContext.getGroups() != null && audience.getGroups() != null) { for (String group : targetingContext.getGroups()) { if (targetGroup(audience, targetingContext, context, group)) { return true; } } } String defaultContextId = targetingContext.getUserId() + "\n" + context.getFeatureName(); return isTargeted(defaultContextId, audience.getDefaultRolloutPercentage()); }
class TargetingFilter implements FeatureFilter { private static final Logger LOGGER = LoggerFactory.getLogger(TargetingFilter.class); /** * users field in the filter */ protected static final String USERS = "users"; /** * groups field in the filter */ protected static final String GROUPS = "groups"; /** * Audience in the filter */ protected static final String AUDIENCE = "Audience"; /** * Audience that always returns false */ protected static final String EXCLUSION = "exclusion"; private static final String EXCLUSION_CAMEL = "Exclusion"; /** * Error message for when the total Audience value is greater than 100 percent. */ protected static final String OUT_OF_RANGE = "The value is out of the accepted range."; private static final String REQUIRED_PARAMETER = "Value cannot be null."; /** * Object Mapper for converting configurations to features */ protected static final ObjectMapper OBJECT_MAPPER = JsonMapper.builder() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true).build(); /** * Accessor for identifying the current user/group when evaluating */ protected final TargetingContextAccessor contextAccessor; /** * Options for evaluating the filter */ protected final TargetingEvaluationOptions options; /** * Filter for targeting a user/group/percentage of users. * * @param contextAccessor Accessor for identifying the current user/group when evaluating */ public TargetingFilter(TargetingContextAccessor contextAccessor) { this.contextAccessor = contextAccessor; this.options = new TargetingEvaluationOptions(); } /** * `Microsoft.TargetingFilter` evaluates a user/group/overall rollout of a feature. * * @param contextAccessor Context for evaluating the users/groups. * @param options enables customization of the filter. */ public TargetingFilter(TargetingContextAccessor contextAccessor, TargetingEvaluationOptions options) { this.contextAccessor = contextAccessor; this.options = options; } @Override @SuppressWarnings("unchecked") private String getKeyFormat(Map<String, Object> parameters, String key) { if (parameters != null && parameters.containsKey(key)) { return key; } return key.toLowerCase(Locale.getDefault()); } private boolean targetUser(String userId, List<String> users) { return userId != null && users != null && users.stream().anyMatch(user -> equals(userId, user)); } private boolean targetGroup(Audience audience, TargetingFilterContext targetingContext, FeatureFilterEvaluationContext context, String group) { Optional<GroupRollout> groupRollout = audience.getGroups().stream() .filter(g -> equals(g.getName(), group)).findFirst(); if (groupRollout.isPresent()) { String audienceContextId = targetingContext.getUserId() + "\n" + context.getName() + "\n" + group; if (isTargeted(audienceContextId, groupRollout.get().getRolloutPercentage())) { return true; } } return false; } private boolean validateTargetingContext(TargetingFilterContext targetingContext) { boolean hasUserDefined = StringUtils.hasText(targetingContext.getUserId()); boolean hasGroupsDefined = targetingContext.getGroups() != null; boolean hasAtLeastOneGroup = false; if (hasGroupsDefined) { hasAtLeastOneGroup = targetingContext.getGroups().stream().anyMatch(group -> StringUtils.hasText(group)); } return (!hasUserDefined && !(hasGroupsDefined && hasAtLeastOneGroup)); } /** * Computes the percentage that the contextId falls into. * * @param contextId Id of the context being targeted * @return the bucket value of the context id * @throws TargetingException Unable to create hash of target context */ protected double isTargetedPercentage(String contextId) { byte[] hash = null; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); hash = digest.digest(contextId.getBytes(Charset.defaultCharset())); } catch (NoSuchAlgorithmException e) { throw new TargetingException("Unable to find SHA-256 for targeting.", e); } if (hash == null) { throw new TargetingException("Unable to create Targeting Hash for " + contextId); } ByteBuffer wrapped = ByteBuffer.wrap(hash); int contextMarker = Math.abs(wrapped.getInt()); return (contextMarker / (double) Integer.MAX_VALUE) * 100; } private boolean isTargeted(String contextId, double percentage) { return isTargetedPercentage(contextId) < percentage; } /** * Validates the settings of a targeting filter. * * @param settings targeting filter settings * @throws TargetingException when a required parameter is missing or percentage value is greater than 100. */ void validateSettings(Audience audience) { String paramName = ""; String reason = ""; if (audience == null) { paramName = AUDIENCE; reason = REQUIRED_PARAMETER; throw new TargetingException(paramName + " : " + reason); } if (audience.getDefaultRolloutPercentage() < 0 || audience.getDefaultRolloutPercentage() > 100) { paramName = AUDIENCE + "." + audience.getDefaultRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } List<GroupRollout> groups = audience.getGroups(); if (groups != null) { for (int index = 0; index < groups.size(); index++) { GroupRollout groupRollout = groups.get(index); if (groupRollout.getRolloutPercentage() < 0 || groupRollout.getRolloutPercentage() > 100) { paramName = AUDIENCE + "[" + index + "]." + groups.get(index).getRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } } } } /** * Checks if two strings are equal, ignores case if configured to. * * @param s1 string to compare * @param s2 string to compare * @return true if the strings are equal */ private boolean equals(String s1, String s2) { if (options.isIgnoreCase()) { return s1.equalsIgnoreCase(s2); } return s1.equals(s2); } /** * Looks at the given key in the parameters and coverts it to a list if it is currently a map. Used for updating * fields in the targeting filter. * * @param <T> Type of object inside of parameters for the given key * @param parameters map of generic objects * @param key key of object int the parameters map */ @SuppressWarnings("unchecked") private void updateValueFromMapToList(Map<String, Object> parameters, String key) { Object objectMap = parameters.get(key); if (objectMap instanceof Map) { Collection<Object> toType = ((Map<String, Object>) objectMap).values(); parameters.put(key, toType); } } }
class TargetingFilter implements FeatureFilter { private static final Logger LOGGER = LoggerFactory.getLogger(TargetingFilter.class); /** * users field in the filter */ protected static final String USERS = "users"; /** * groups field in the filter */ protected static final String GROUPS = "groups"; /** * Audience in the filter */ protected static final String AUDIENCE = "Audience"; /** * Audience that always returns false */ protected static final String EXCLUSION = "exclusion"; private static final String EXCLUSION_CAMEL = "Exclusion"; /** * Error message for when the total Audience value is greater than 100 percent. */ protected static final String OUT_OF_RANGE = "The value is out of the accepted range."; private static final String REQUIRED_PARAMETER = "Value cannot be null."; /** * Object Mapper for converting configurations to features */ protected static final ObjectMapper OBJECT_MAPPER = JsonMapper.builder() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true).build(); /** * Accessor for identifying the current user/group when evaluating */ protected final TargetingContextAccessor contextAccessor; /** * Options for evaluating the filter */ protected final TargetingEvaluationOptions options; /** * Filter for targeting a user/group/percentage of users. * * @param contextAccessor Accessor for identifying the current user/group when evaluating */ public TargetingFilter(TargetingContextAccessor contextAccessor) { this.contextAccessor = contextAccessor; this.options = new TargetingEvaluationOptions(); } /** * `Microsoft.TargetingFilter` evaluates a user/group/overall rollout of a feature. * * @param contextAccessor Context for evaluating the users/groups. * @param options enables customization of the filter. */ public TargetingFilter(TargetingContextAccessor contextAccessor, TargetingEvaluationOptions options) { this.contextAccessor = contextAccessor; this.options = options; } @Override @SuppressWarnings("unchecked") private String getKeyCase(Map<String, Object> parameters, String key) { if (parameters != null && parameters.containsKey(key)) { return key; } return key.toLowerCase(Locale.getDefault()); } private boolean targetUser(String userId, List<String> users) { return userId != null && users != null && users.stream().anyMatch(user -> equals(userId, user)); } private boolean targetGroup(Audience audience, TargetingFilterContext targetingContext, FeatureFilterEvaluationContext context, String group) { Optional<GroupRollout> groupRollout = audience.getGroups().stream() .filter(g -> equals(g.getName(), group)).findFirst(); if (groupRollout.isPresent()) { String audienceContextId = targetingContext.getUserId() + "\n" + context.getName() + "\n" + group; if (isTargeted(audienceContextId, groupRollout.get().getRolloutPercentage())) { return true; } } return false; } private boolean validateTargetingContext(TargetingFilterContext targetingContext) { boolean hasUserDefined = StringUtils.hasText(targetingContext.getUserId()); boolean hasGroupsDefined = targetingContext.getGroups() != null; boolean hasAtLeastOneGroup = false; if (hasGroupsDefined) { hasAtLeastOneGroup = targetingContext.getGroups().stream().anyMatch(group -> StringUtils.hasText(group)); } return (!hasUserDefined && !(hasGroupsDefined && hasAtLeastOneGroup)); } /** * Computes the percentage that the contextId falls into. * * @param contextId Id of the context being targeted * @return the bucket value of the context id * @throws TargetingException Unable to create hash of target context */ protected double isTargetedPercentage(String contextId) { byte[] hash = null; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); hash = digest.digest(contextId.getBytes(Charset.defaultCharset())); } catch (NoSuchAlgorithmException e) { throw new TargetingException("Unable to find SHA-256 for targeting.", e); } if (hash == null) { throw new TargetingException("Unable to create Targeting Hash for " + contextId); } ByteBuffer wrapped = ByteBuffer.wrap(hash); int contextMarker = Math.abs(wrapped.getInt()); return (contextMarker / (double) Integer.MAX_VALUE) * 100; } private boolean isTargeted(String contextId, double percentage) { return isTargetedPercentage(contextId) < percentage; } /** * Validates the settings of a targeting filter. * * @param settings targeting filter settings * @throws TargetingException when a required parameter is missing or percentage value is greater than 100. */ void validateSettings(Audience audience) { String paramName = ""; String reason = ""; if (audience == null) { paramName = AUDIENCE; reason = REQUIRED_PARAMETER; throw new TargetingException(paramName + " : " + reason); } if (audience.getDefaultRolloutPercentage() < 0 || audience.getDefaultRolloutPercentage() > 100) { paramName = AUDIENCE + "." + audience.getDefaultRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } List<GroupRollout> groups = audience.getGroups(); if (groups != null) { for (int index = 0; index < groups.size(); index++) { GroupRollout groupRollout = groups.get(index); if (groupRollout.getRolloutPercentage() < 0 || groupRollout.getRolloutPercentage() > 100) { paramName = AUDIENCE + "[" + index + "]." + groups.get(index).getRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } } } } /** * Checks if two strings are equal, ignores case if configured to. * * @param s1 string to compare * @param s2 string to compare * @return true if the strings are equal */ private boolean equals(String s1, String s2) { if (options.isIgnoreCase()) { return s1.equalsIgnoreCase(s2); } return s1.equals(s2); } /** * Looks at the given key in the parameters and coverts it to a list if it is currently a map. Used for updating * fields in the targeting filter. * * @param <T> Type of object inside of parameters for the given key * @param parameters map of generic objects * @param key key of object int the parameters map */ @SuppressWarnings("unchecked") private void updateValueFromMapToList(Map<String, Object> parameters, String key) { Object objectMap = parameters.get(key); if (objectMap instanceof Map) { Collection<Object> toType = ((Map<String, Object>) objectMap).values(); parameters.put(key, toType); } } }
I think that for the sake of clarity, I would get rid of printing the token usage. Instead, I would either by adding comments or doing the actual calls, show that we should check the `finish_reason == "function_call"` and if that is the case, we should send the result of the locally called function back to the LLM.
public static void main(String[] args) { String azureOpenaiKey = "{azure-open-ai-key}"; String endpoint = "{azure-open-ai-endpoint}"; String deploymentOrModelId = "{azure-open-ai-deployment-model-id}"; OpenAIClient client = new OpenAIClientBuilder() .endpoint(endpoint) .credential(new AzureKeyCredential(azureOpenaiKey)) .buildClient(); List<FunctionDefinition> functions = Arrays.asList( new FunctionDefinition("MyFunction").setParameters(new Parameters()) ); List<ChatMessage> chatMessages = Arrays.asList( new ChatMessage(ChatRole.USER, "What's the weather like in San Francisco in Celsius?") ); ChatCompletionsOptions chatCompletionOptions = new ChatCompletionsOptions(chatMessages) .setFunctionCall(FunctionCallConfig.AUTO) .setFunctions(functions); ChatCompletions chatCompletions = client.getChatCompletions(deploymentOrModelId, chatCompletionOptions); System.out.printf("Model ID=%s is created at %d.%n", chatCompletions.getId(), chatCompletions.getCreatedAt()); for (ChatChoice choice : chatCompletions.getChoices()) { ChatMessage message = choice.getMessage(); System.out.printf("Index: %d, Chat Role: %s.%n", choice.getIndex(), message.getRole()); FunctionCall functionCall = message.getFunctionCall(); System.out.printf("Function name: %s, arguments: %s.%n", functionCall.getName(), functionCall.getArguments()); } System.out.println(); CompletionsUsage usage = chatCompletions.getUsage(); System.out.printf("Usage: number of prompt token is %d, " + "number of completion token is %d, and number of total tokens in request and response is %d.%n", usage.getPromptTokens(), usage.getCompletionTokens(), usage.getTotalTokens()); }
System.out.printf("Usage: number of prompt token is %d, "
public static void main(String[] args) { String azureOpenaiKey = "{azure-open-ai-key}"; String endpoint = "{azure-open-ai-endpoint}"; String deploymentOrModelId = "{azure-open-ai-deployment-model-id}"; OpenAIClient client = new OpenAIClientBuilder() .endpoint(endpoint) .credential(new AzureKeyCredential(azureOpenaiKey)) .buildClient(); List<FunctionDefinition> functions = Arrays.asList( new FunctionDefinition("getCurrentWeather") .setDescription("Get the current weather") .setParameters(getFunctionDefinition()) ); List<ChatMessage> chatMessages = new ArrayList<>(); chatMessages.add(new ChatMessage(ChatRole.USER, "What should I wear in Boston depending on the weather?")); ChatCompletionsOptions chatCompletionOptions = new ChatCompletionsOptions(chatMessages) .setFunctionCall(FunctionCallConfig.AUTO) .setFunctions(functions); ChatCompletions chatCompletions = client.getChatCompletions(deploymentOrModelId, chatCompletionOptions); List<ChatMessage> chatMessages2 = handleFunctionCallResponse(chatCompletions.getChoices(), chatMessages); ChatCompletionsOptions chatCompletionOptions2 = new ChatCompletionsOptions(chatMessages2); ChatCompletions chatCompletions2 = client.getChatCompletions(deploymentOrModelId, chatCompletionOptions2); List<ChatChoice> choices = chatCompletions2.getChoices(); ChatMessage message = choices.get(0).getMessage(); System.out.printf("Message: %s.%n", message.getContent()); }
class FunctionCallSample { /** * Runs the sample algorithm and demonstrates how to get chat completions using function call. * * @param args Unused. Arguments to the program. */ }
class FunctionCallSample { /** * Runs the sample algorithm and demonstrates how to get chat completions using function call. * * @param args Unused. Arguments to the program. */ private static Map<String, Object> getFunctionDefinition() { Map<String, Object> location = new HashMap<>(); location.put("type", "string"); location.put("description", "The city and state, e.g. San Francisco, CA"); Map<String, Object> unit = new HashMap<>(); unit.put("type", "string"); unit.put("enum", Arrays.asList("celsius", "fahrenheit")); Map<String, Object> prop1 = new HashMap<>(); prop1.put("location", location); prop1.put("unit", unit); Map<String, Object> functionDefinition = new HashMap<>(); functionDefinition.put("type", "object"); functionDefinition.put("required", Arrays.asList("location", "unit")); functionDefinition.put("properties", prop1); return functionDefinition; } private static List<ChatMessage> handleFunctionCallResponse(List<ChatChoice> choices, List<ChatMessage> chatMessages) { for (ChatChoice choice : choices) { ChatMessage choiceMessage = choice.getMessage(); FunctionCall functionCall = choiceMessage.getFunctionCall(); if (CompletionsFinishReason.FUNCTION_CALL.equals(choice.getFinishReason())) { System.out.printf("Function name: %s, arguments: %s.%n", functionCall.getName(), functionCall.getArguments()); WeatherLocation weatherLocation = BinaryData.fromString(functionCall.getArguments()).toObject(WeatherLocation.class); int currentWeather = getCurrentWeather(weatherLocation); chatMessages.add(new ChatMessage(ChatRole.USER, String.format("The weather in %s is %d degrees %s.", weatherLocation.getLocation(), currentWeather, weatherLocation.getUnit()))); } else { chatMessages.add(choiceMessage); } } return chatMessages; } private static int getCurrentWeather(WeatherLocation weatherLocation) { return 35; } private static class WeatherLocation { @JsonProperty(value = "unit") String unit; @JsonProperty(value = "location") String location; @JsonCreator WeatherLocation(@JsonProperty(value = "unit") String unit, @JsonProperty(value = "location") String location) { this.unit = unit; this.location = location; } public String getUnit() { return unit; } public String getLocation() { return location; } } }
I'll change the code once the new version of Core Test is released.
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( MapsRenderClientBuilder.RENDER_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER)));
HttpPipeline getHttpPipeline(HttpClient httpClient) { httpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; if (interceptorManager.isRecordMode() || interceptorManager.isPlaybackMode()) { interceptorManager.addSanitizers( Collections.singletonList( new TestProxySanitizer("subscription-key", ".+", "REDACTED", TestProxySanitizerType.HEADER))); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("subscription-key"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy(new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)))); policies.add( new AzureKeyCredentialPolicy( MapsRenderClientBuilder.RENDER_SUBSCRIPTION_KEY, new AzureKeyCredential(interceptorManager.isPlaybackMode() ? FAKE_API_KEY : Configuration.getGlobalConfiguration().get("SUBSCRIPTION_KEY")))); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
class MapsRenderClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } MapsRenderClientBuilder getRenderAsyncClientBuilder(HttpClient httpClient, MapsRenderServiceVersion serviceVersion) { MapsRenderClientBuilder builder = new MapsRenderClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetMapTile(byte[] actual) { assertNotNull(actual); assertTrue(actual.length > 0); } static void validateGetMapTileWithResponse(int expectedStatusCode, Response<BinaryData> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapTile(response.getValue().toBytes()); } static void validateGetMapTileset(MapTileset expected, MapTileset actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getMinZoom(), actual.getMinZoom()); } static void validateGetMapTilesetWithResponse(MapTileset expected, int expectedStatusCode, Response<MapTileset> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapTileset(expected, response.getValue()); } static void validateGetMapAttribution(MapAttribution expected, MapAttribution actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCopyrights().size(), actual.getCopyrights().size()); } static void validateGetMapAttributionWithResponse(MapAttribution expected, int expectedStatusCode, Response<MapAttribution> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapAttribution(expected, response.getValue()); } static void validateGetCopyrightCaption(CopyrightCaption expected, CopyrightCaption actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); } static void validateGetCopyrightCaptionWithResponse(CopyrightCaption expected, int expectedStatusCode, Response<CopyrightCaption> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightCaption(expected, response.getValue()); } static void validateGetCopyrightCaptionFromBoundingBox(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); assertEquals(expected.getRegions().size(), actual.getRegions().size()); } static void validateGetCopyrightCaptionFromBoundingBoxWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightCaptionFromBoundingBox(expected, response.getValue()); } static void validateGetMapStaticImage(byte[] actual) { assertNotNull(actual); assertTrue(actual.length > 0); } static void validateGetMapStaticImageWithResponse(int expectedStatusCode, Response<BinaryData> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapStaticImage(response.getValue().toBytes()); } static void validateGetCopyrightForTile(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); assertEquals(expected.getRegions().size(), actual.getRegions().size()); } static void validateGetCopyrightForTileWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightForTile(expected, response.getValue()); } static void validateGetCopyrightForWorld(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); } static void validateGetCopyrightForWorldWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightForWorld(expected, response.getValue()); } }
class MapsRenderClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; static InterceptorManager interceptorManagerTestBase; Duration durationTestMode; @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = Duration.ofMillis(1); } else { durationTestMode = TestUtils.DEFAULT_POLL_INTERVAL; } interceptorManagerTestBase = interceptorManager; } MapsRenderClientBuilder getRenderAsyncClientBuilder(HttpClient httpClient, MapsRenderServiceVersion serviceVersion) { MapsRenderClientBuilder builder = new MapsRenderClientBuilder() .pipeline(getHttpPipeline(httpClient)) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (interceptorManager.isPlaybackMode()) { builder.endpoint("https: } return builder; } static void validateGetMapTile(byte[] actual) { assertNotNull(actual); assertTrue(actual.length > 0); } static void validateGetMapTileWithResponse(int expectedStatusCode, Response<BinaryData> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapTile(response.getValue().toBytes()); } static void validateGetMapTileset(MapTileset expected, MapTileset actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getMinZoom(), actual.getMinZoom()); } static void validateGetMapTilesetWithResponse(MapTileset expected, int expectedStatusCode, Response<MapTileset> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapTileset(expected, response.getValue()); } static void validateGetMapAttribution(MapAttribution expected, MapAttribution actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getCopyrights().size(), actual.getCopyrights().size()); } static void validateGetMapAttributionWithResponse(MapAttribution expected, int expectedStatusCode, Response<MapAttribution> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapAttribution(expected, response.getValue()); } static void validateGetCopyrightCaption(CopyrightCaption expected, CopyrightCaption actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); } static void validateGetCopyrightCaptionWithResponse(CopyrightCaption expected, int expectedStatusCode, Response<CopyrightCaption> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightCaption(expected, response.getValue()); } static void validateGetCopyrightCaptionFromBoundingBox(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); assertEquals(expected.getRegions().size(), actual.getRegions().size()); } static void validateGetCopyrightCaptionFromBoundingBoxWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightCaptionFromBoundingBox(expected, response.getValue()); } static void validateGetMapStaticImage(byte[] actual) { assertNotNull(actual); assertTrue(actual.length > 0); } static void validateGetMapStaticImageWithResponse(int expectedStatusCode, Response<BinaryData> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetMapStaticImage(response.getValue().toBytes()); } static void validateGetCopyrightForTile(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); assertEquals(expected.getRegions().size(), actual.getRegions().size()); } static void validateGetCopyrightForTileWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightForTile(expected, response.getValue()); } static void validateGetCopyrightForWorld(Copyright expected, Copyright actual) { assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getFormatVersion(), actual.getFormatVersion()); assertEquals(expected.getGeneralCopyrights().size(), actual.getGeneralCopyrights().size()); } static void validateGetCopyrightForWorldWithResponse(Copyright expected, int expectedStatusCode, Response<Copyright> response) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); validateGetCopyrightForWorld(expected, response.getValue()); } }
Now we will only add the claims if CAE is enabled and there are claims? Are there no cases where there was previously a claim that we need to honor that is not a CAE situation?
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); }
if (request.isCaeEnabled() && request.getClaims() != null) {
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); }
class IdentityClient extends IdentityClientBase { private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> workloadIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { super(tenantId, clientId, clientSecret, certificatePath, clientAssertionFilePath, resourceId, clientAssertionSupplier, certificate, certificatePassword, isSharedTokenCacheCredential, clientAssertionTimeout, options); this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, false)); this.publicClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, true)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(false)); this.confidentialClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(true)); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getManagedIdentityConfidentialClientApplication); this.workloadIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getWorkloadIdentityConfidentialClientApplication); Duration cacheTimeout = (clientAssertionTimeout == null) ? Duration.ofMinutes(5) : clientAssertionTimeout; this.clientAssertionAccessor = new SynchronizedAccessor<>(this::parseClientAssertion, cacheTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication(boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getConfidentialClient(enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getManagedIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getWorkloadIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getWorkloadIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } @Override Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential, boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getPublicClient(sharedTokenCacheCredential, enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azCommand.append(" --tenant ").append(tenant); } } catch (ClientAuthenticationException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureCLIAuthentication(azCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Developer CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureDeveloperCli(TokenRequestContext request) { StringBuilder azdCommand = new StringBuilder("azd auth token --output json --scope "); List<String> scopes = request.getScopes(); if (scopes.size() == 0) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException("Missing scope in request"))); } azdCommand.append(String.join(" --scope ", scopes)); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azdCommand.append(" --tenant-id ").append(tenant); } } catch (ClientAuthenticationException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureDeveloperCLIAuthentication(azdCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(buildOBOFlowParameters(request))) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); String command = "Get-AzAccessToken -ResourceUrl " + ScopeUtil.scopesToResource(request.getScopes()) + " | ConvertTo-Json"; LOGGER.verbose("Azure Powershell Authentication => Executing the command `{}` in Azure " + "Powershell to retrieve the Access Token.", command); return manager.runCommand(command) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = buildConfidentialClientParameters(request); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private SynchronizedAccessor<ConfidentialClientApplication> getConfidentialClientInstance(TokenRequestContext requestContext) { return requestContext.isCaeEnabled() ? confidentialClientApplicationAccessorWithCae : confidentialClientApplicationAccessor; } private ClientCredentialParameters.ClientCredentialParametersBuilder buildConfidentialClientParameters(TokenRequestContext request) { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder; } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } public Mono<AccessToken> authenticateWithWorkloadIdentityConfidentialClient(TokenRequestContext request) { return workloadIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = buildUsernamePasswordFlowParameters(request, username, password); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") private SynchronizedAccessor<PublicClientApplication> getPublicClientInstance(TokenRequestContext request) { return request.isCaeEnabled() ? publicClientApplicationAccessorWithCae : publicClientApplicationAccessor; } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return getPublicClientInstance(request).getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = buildDeviceCodeFlowParameters(request, deviceCodeConsumer); return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code.", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = getConfidentialClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = buildInteractiveRequestParameters(request, loginHint, redirectUri); SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); Mono<IAuthenticationResult> acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(pc::getAccounts)) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { accounts.putIfAbsent(cached.homeAccountId(), cached); } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication unavailable. " + "Multiple accounts were found in the cache. Use username and tenant id to disambiguate.") ); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; String payload = identityEndpoint + "?resource=" + urlEncode(ScopeUtil.scopesToResource(request.getScopes())) + "&api-version=" + ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION; URL url = getUrl(payload); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", "Basic " + secretKey); connection.setRequestProperty("Metadata", "true"); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> authenticateWithExchangeTokenHelper(request, assertionToken))); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(1024) .append(identityEndpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (identityHeader != null) { connection.setRequestProperty("Secret", identityHeader); } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * <p> * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(1024) .append(endpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(urlEncode(clientId)); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version=2018-02-01"); payload.append("&resource="); payload.append(urlEncode(resource)); if (clientId != null) { payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(endpoint + "?" + payload); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( "Could not connect to the url: " + url + ".", exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(ThreadLocalRandom.current().nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(endpoint + "?api-version=2018-02-01"); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return ADFS_TENANT.equals(this.tenantId); } Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider() { return appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = authenticateWithExchangeToken(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }; } }
class IdentityClient extends IdentityClientBase { private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> workloadIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { super(tenantId, clientId, clientSecret, certificatePath, clientAssertionFilePath, resourceId, clientAssertionSupplier, certificate, certificatePassword, isSharedTokenCacheCredential, clientAssertionTimeout, options); this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, false)); this.publicClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, true)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(false)); this.confidentialClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(true)); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getManagedIdentityConfidentialClientApplication); this.workloadIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getWorkloadIdentityConfidentialClientApplication); Duration cacheTimeout = (clientAssertionTimeout == null) ? Duration.ofMinutes(5) : clientAssertionTimeout; this.clientAssertionAccessor = new SynchronizedAccessor<>(this::parseClientAssertion, cacheTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication(boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getConfidentialClient(enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getManagedIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getWorkloadIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getWorkloadIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } @Override Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential, boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getPublicClient(sharedTokenCacheCredential, enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azCommand.append(" --tenant ").append(tenant); } } catch (ClientAuthenticationException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureCLIAuthentication(azCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Developer CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureDeveloperCli(TokenRequestContext request) { StringBuilder azdCommand = new StringBuilder("azd auth token --output json --scope "); List<String> scopes = request.getScopes(); if (scopes.size() == 0) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException("Missing scope in request"))); } azdCommand.append(String.join(" --scope ", scopes)); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azdCommand.append(" --tenant-id ").append(tenant); } } catch (ClientAuthenticationException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureDeveloperCLIAuthentication(azdCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(buildOBOFlowParameters(request))) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); String command = "Get-AzAccessToken -ResourceUrl " + ScopeUtil.scopesToResource(request.getScopes()) + " | ConvertTo-Json"; LOGGER.verbose("Azure Powershell Authentication => Executing the command `{}` in Azure " + "Powershell to retrieve the Access Token.", command); return manager.runCommand(command) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = buildConfidentialClientParameters(request); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private SynchronizedAccessor<ConfidentialClientApplication> getConfidentialClientInstance(TokenRequestContext requestContext) { return requestContext.isCaeEnabled() ? confidentialClientApplicationAccessorWithCae : confidentialClientApplicationAccessor; } private ClientCredentialParameters.ClientCredentialParametersBuilder buildConfidentialClientParameters(TokenRequestContext request) { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder; } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } public Mono<AccessToken> authenticateWithWorkloadIdentityConfidentialClient(TokenRequestContext request) { return workloadIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = buildUsernamePasswordFlowParameters(request, username, password); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") private SynchronizedAccessor<PublicClientApplication> getPublicClientInstance(TokenRequestContext request) { return request.isCaeEnabled() ? publicClientApplicationAccessorWithCae : publicClientApplicationAccessor; } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return getPublicClientInstance(request).getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = buildDeviceCodeFlowParameters(request, deviceCodeConsumer); return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code.", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = getConfidentialClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = buildInteractiveRequestParameters(request, loginHint, redirectUri); SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); Mono<IAuthenticationResult> acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(pc::getAccounts)) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { accounts.putIfAbsent(cached.homeAccountId(), cached); } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication unavailable. " + "Multiple accounts were found in the cache. Use username and tenant id to disambiguate.") ); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; String payload = identityEndpoint + "?resource=" + urlEncode(ScopeUtil.scopesToResource(request.getScopes())) + "&api-version=" + ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION; URL url = getUrl(payload); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", "Basic " + secretKey); connection.setRequestProperty("Metadata", "true"); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> authenticateWithExchangeTokenHelper(request, assertionToken))); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(1024) .append(identityEndpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (identityHeader != null) { connection.setRequestProperty("Secret", identityHeader); } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * <p> * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(1024) .append(endpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(urlEncode(clientId)); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version=2018-02-01"); payload.append("&resource="); payload.append(urlEncode(resource)); if (clientId != null) { payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(endpoint + "?" + payload); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( "Could not connect to the url: " + url + ".", exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(ThreadLocalRandom.current().nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(endpoint + "?api-version=2018-02-01"); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return ADFS_TENANT.equals(this.tenantId); } Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider() { return appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = authenticateWithExchangeToken(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }; } }
previously, it was enabled by default for Public client auth. With this change, it is disabled by default, and needs to be enabled via the TRC parameter. This will be a behavioral breaking change, being done by design across languages. We should update TSG with this info.
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); }
if (request.isCaeEnabled() && request.getClaims() != null) {
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); }
class IdentityClient extends IdentityClientBase { private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> workloadIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { super(tenantId, clientId, clientSecret, certificatePath, clientAssertionFilePath, resourceId, clientAssertionSupplier, certificate, certificatePassword, isSharedTokenCacheCredential, clientAssertionTimeout, options); this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, false)); this.publicClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, true)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(false)); this.confidentialClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(true)); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getManagedIdentityConfidentialClientApplication); this.workloadIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getWorkloadIdentityConfidentialClientApplication); Duration cacheTimeout = (clientAssertionTimeout == null) ? Duration.ofMinutes(5) : clientAssertionTimeout; this.clientAssertionAccessor = new SynchronizedAccessor<>(this::parseClientAssertion, cacheTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication(boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getConfidentialClient(enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getManagedIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getWorkloadIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getWorkloadIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } @Override Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential, boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getPublicClient(sharedTokenCacheCredential, enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azCommand.append(" --tenant ").append(tenant); } } catch (ClientAuthenticationException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureCLIAuthentication(azCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Developer CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureDeveloperCli(TokenRequestContext request) { StringBuilder azdCommand = new StringBuilder("azd auth token --output json --scope "); List<String> scopes = request.getScopes(); if (scopes.size() == 0) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException("Missing scope in request"))); } azdCommand.append(String.join(" --scope ", scopes)); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azdCommand.append(" --tenant-id ").append(tenant); } } catch (ClientAuthenticationException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureDeveloperCLIAuthentication(azdCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(buildOBOFlowParameters(request))) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); String command = "Get-AzAccessToken -ResourceUrl " + ScopeUtil.scopesToResource(request.getScopes()) + " | ConvertTo-Json"; LOGGER.verbose("Azure Powershell Authentication => Executing the command `{}` in Azure " + "Powershell to retrieve the Access Token.", command); return manager.runCommand(command) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = buildConfidentialClientParameters(request); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private SynchronizedAccessor<ConfidentialClientApplication> getConfidentialClientInstance(TokenRequestContext requestContext) { return requestContext.isCaeEnabled() ? confidentialClientApplicationAccessorWithCae : confidentialClientApplicationAccessor; } private ClientCredentialParameters.ClientCredentialParametersBuilder buildConfidentialClientParameters(TokenRequestContext request) { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder; } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } public Mono<AccessToken> authenticateWithWorkloadIdentityConfidentialClient(TokenRequestContext request) { return workloadIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = buildUsernamePasswordFlowParameters(request, username, password); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") private SynchronizedAccessor<PublicClientApplication> getPublicClientInstance(TokenRequestContext request) { return request.isCaeEnabled() ? publicClientApplicationAccessorWithCae : publicClientApplicationAccessor; } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return getPublicClientInstance(request).getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = buildDeviceCodeFlowParameters(request, deviceCodeConsumer); return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code.", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = getConfidentialClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = buildInteractiveRequestParameters(request, loginHint, redirectUri); SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); Mono<IAuthenticationResult> acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(pc::getAccounts)) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { accounts.putIfAbsent(cached.homeAccountId(), cached); } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication unavailable. " + "Multiple accounts were found in the cache. Use username and tenant id to disambiguate.") ); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; String payload = identityEndpoint + "?resource=" + urlEncode(ScopeUtil.scopesToResource(request.getScopes())) + "&api-version=" + ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION; URL url = getUrl(payload); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", "Basic " + secretKey); connection.setRequestProperty("Metadata", "true"); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> authenticateWithExchangeTokenHelper(request, assertionToken))); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(1024) .append(identityEndpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (identityHeader != null) { connection.setRequestProperty("Secret", identityHeader); } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * <p> * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(1024) .append(endpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(urlEncode(clientId)); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version=2018-02-01"); payload.append("&resource="); payload.append(urlEncode(resource)); if (clientId != null) { payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(endpoint + "?" + payload); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( "Could not connect to the url: " + url + ".", exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(ThreadLocalRandom.current().nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(endpoint + "?api-version=2018-02-01"); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return ADFS_TENANT.equals(this.tenantId); } Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider() { return appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = authenticateWithExchangeToken(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }; } }
class IdentityClient extends IdentityClientBase { private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> workloadIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { super(tenantId, clientId, clientSecret, certificatePath, clientAssertionFilePath, resourceId, clientAssertionSupplier, certificate, certificatePassword, isSharedTokenCacheCredential, clientAssertionTimeout, options); this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, false)); this.publicClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, true)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(false)); this.confidentialClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(true)); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getManagedIdentityConfidentialClientApplication); this.workloadIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getWorkloadIdentityConfidentialClientApplication); Duration cacheTimeout = (clientAssertionTimeout == null) ? Duration.ofMinutes(5) : clientAssertionTimeout; this.clientAssertionAccessor = new SynchronizedAccessor<>(this::parseClientAssertion, cacheTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication(boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getConfidentialClient(enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getManagedIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getWorkloadIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getWorkloadIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } @Override Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential, boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getPublicClient(sharedTokenCacheCredential, enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azCommand.append(" --tenant ").append(tenant); } } catch (ClientAuthenticationException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureCLIAuthentication(azCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Developer CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureDeveloperCli(TokenRequestContext request) { StringBuilder azdCommand = new StringBuilder("azd auth token --output json --scope "); List<String> scopes = request.getScopes(); if (scopes.size() == 0) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException("Missing scope in request"))); } azdCommand.append(String.join(" --scope ", scopes)); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azdCommand.append(" --tenant-id ").append(tenant); } } catch (ClientAuthenticationException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureDeveloperCLIAuthentication(azdCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(buildOBOFlowParameters(request))) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); String command = "Get-AzAccessToken -ResourceUrl " + ScopeUtil.scopesToResource(request.getScopes()) + " | ConvertTo-Json"; LOGGER.verbose("Azure Powershell Authentication => Executing the command `{}` in Azure " + "Powershell to retrieve the Access Token.", command); return manager.runCommand(command) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = buildConfidentialClientParameters(request); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private SynchronizedAccessor<ConfidentialClientApplication> getConfidentialClientInstance(TokenRequestContext requestContext) { return requestContext.isCaeEnabled() ? confidentialClientApplicationAccessorWithCae : confidentialClientApplicationAccessor; } private ClientCredentialParameters.ClientCredentialParametersBuilder buildConfidentialClientParameters(TokenRequestContext request) { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder; } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } public Mono<AccessToken> authenticateWithWorkloadIdentityConfidentialClient(TokenRequestContext request) { return workloadIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = buildUsernamePasswordFlowParameters(request, username, password); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") private SynchronizedAccessor<PublicClientApplication> getPublicClientInstance(TokenRequestContext request) { return request.isCaeEnabled() ? publicClientApplicationAccessorWithCae : publicClientApplicationAccessor; } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return getPublicClientInstance(request).getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = buildDeviceCodeFlowParameters(request, deviceCodeConsumer); return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code.", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = getConfidentialClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = buildInteractiveRequestParameters(request, loginHint, redirectUri); SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); Mono<IAuthenticationResult> acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(pc::getAccounts)) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { accounts.putIfAbsent(cached.homeAccountId(), cached); } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication unavailable. " + "Multiple accounts were found in the cache. Use username and tenant id to disambiguate.") ); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; String payload = identityEndpoint + "?resource=" + urlEncode(ScopeUtil.scopesToResource(request.getScopes())) + "&api-version=" + ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION; URL url = getUrl(payload); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", "Basic " + secretKey); connection.setRequestProperty("Metadata", "true"); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> authenticateWithExchangeTokenHelper(request, assertionToken))); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(1024) .append(identityEndpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (identityHeader != null) { connection.setRequestProperty("Secret", identityHeader); } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * <p> * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(1024) .append(endpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(urlEncode(clientId)); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version=2018-02-01"); payload.append("&resource="); payload.append(urlEncode(resource)); if (clientId != null) { payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(endpoint + "?" + payload); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( "Could not connect to the url: " + url + ".", exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(ThreadLocalRandom.current().nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(endpoint + "?api-version=2018-02-01"); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return ADFS_TENANT.equals(this.tenantId); } Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider() { return appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = authenticateWithExchangeToken(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }; } }
Will you include the TSG update here or in another change?
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); }
if (request.isCaeEnabled() && request.getClaims() != null) {
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); }
class IdentityClient extends IdentityClientBase { private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> workloadIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { super(tenantId, clientId, clientSecret, certificatePath, clientAssertionFilePath, resourceId, clientAssertionSupplier, certificate, certificatePassword, isSharedTokenCacheCredential, clientAssertionTimeout, options); this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, false)); this.publicClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, true)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(false)); this.confidentialClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(true)); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getManagedIdentityConfidentialClientApplication); this.workloadIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getWorkloadIdentityConfidentialClientApplication); Duration cacheTimeout = (clientAssertionTimeout == null) ? Duration.ofMinutes(5) : clientAssertionTimeout; this.clientAssertionAccessor = new SynchronizedAccessor<>(this::parseClientAssertion, cacheTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication(boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getConfidentialClient(enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getManagedIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getWorkloadIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getWorkloadIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } @Override Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential, boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getPublicClient(sharedTokenCacheCredential, enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azCommand.append(" --tenant ").append(tenant); } } catch (ClientAuthenticationException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureCLIAuthentication(azCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Developer CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureDeveloperCli(TokenRequestContext request) { StringBuilder azdCommand = new StringBuilder("azd auth token --output json --scope "); List<String> scopes = request.getScopes(); if (scopes.size() == 0) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException("Missing scope in request"))); } azdCommand.append(String.join(" --scope ", scopes)); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azdCommand.append(" --tenant-id ").append(tenant); } } catch (ClientAuthenticationException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureDeveloperCLIAuthentication(azdCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(buildOBOFlowParameters(request))) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); String command = "Get-AzAccessToken -ResourceUrl " + ScopeUtil.scopesToResource(request.getScopes()) + " | ConvertTo-Json"; LOGGER.verbose("Azure Powershell Authentication => Executing the command `{}` in Azure " + "Powershell to retrieve the Access Token.", command); return manager.runCommand(command) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = buildConfidentialClientParameters(request); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private SynchronizedAccessor<ConfidentialClientApplication> getConfidentialClientInstance(TokenRequestContext requestContext) { return requestContext.isCaeEnabled() ? confidentialClientApplicationAccessorWithCae : confidentialClientApplicationAccessor; } private ClientCredentialParameters.ClientCredentialParametersBuilder buildConfidentialClientParameters(TokenRequestContext request) { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder; } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } public Mono<AccessToken> authenticateWithWorkloadIdentityConfidentialClient(TokenRequestContext request) { return workloadIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = buildUsernamePasswordFlowParameters(request, username, password); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") private SynchronizedAccessor<PublicClientApplication> getPublicClientInstance(TokenRequestContext request) { return request.isCaeEnabled() ? publicClientApplicationAccessorWithCae : publicClientApplicationAccessor; } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return getPublicClientInstance(request).getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = buildDeviceCodeFlowParameters(request, deviceCodeConsumer); return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code.", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = getConfidentialClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = buildInteractiveRequestParameters(request, loginHint, redirectUri); SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); Mono<IAuthenticationResult> acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(pc::getAccounts)) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { accounts.putIfAbsent(cached.homeAccountId(), cached); } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication unavailable. " + "Multiple accounts were found in the cache. Use username and tenant id to disambiguate.") ); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; String payload = identityEndpoint + "?resource=" + urlEncode(ScopeUtil.scopesToResource(request.getScopes())) + "&api-version=" + ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION; URL url = getUrl(payload); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", "Basic " + secretKey); connection.setRequestProperty("Metadata", "true"); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> authenticateWithExchangeTokenHelper(request, assertionToken))); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(1024) .append(identityEndpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (identityHeader != null) { connection.setRequestProperty("Secret", identityHeader); } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * <p> * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(1024) .append(endpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(urlEncode(clientId)); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version=2018-02-01"); payload.append("&resource="); payload.append(urlEncode(resource)); if (clientId != null) { payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(endpoint + "?" + payload); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( "Could not connect to the url: " + url + ".", exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(ThreadLocalRandom.current().nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(endpoint + "?api-version=2018-02-01"); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return ADFS_TENANT.equals(this.tenantId); } Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider() { return appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = authenticateWithExchangeToken(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }; } }
class IdentityClient extends IdentityClientBase { private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> workloadIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { super(tenantId, clientId, clientSecret, certificatePath, clientAssertionFilePath, resourceId, clientAssertionSupplier, certificate, certificatePassword, isSharedTokenCacheCredential, clientAssertionTimeout, options); this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, false)); this.publicClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, true)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(false)); this.confidentialClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(true)); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getManagedIdentityConfidentialClientApplication); this.workloadIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getWorkloadIdentityConfidentialClientApplication); Duration cacheTimeout = (clientAssertionTimeout == null) ? Duration.ofMinutes(5) : clientAssertionTimeout; this.clientAssertionAccessor = new SynchronizedAccessor<>(this::parseClientAssertion, cacheTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication(boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getConfidentialClient(enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getManagedIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getWorkloadIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getWorkloadIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } @Override Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential, boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getPublicClient(sharedTokenCacheCredential, enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azCommand.append(" --tenant ").append(tenant); } } catch (ClientAuthenticationException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureCLIAuthentication(azCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Developer CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureDeveloperCli(TokenRequestContext request) { StringBuilder azdCommand = new StringBuilder("azd auth token --output json --scope "); List<String> scopes = request.getScopes(); if (scopes.size() == 0) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException("Missing scope in request"))); } azdCommand.append(String.join(" --scope ", scopes)); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azdCommand.append(" --tenant-id ").append(tenant); } } catch (ClientAuthenticationException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureDeveloperCLIAuthentication(azdCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(buildOBOFlowParameters(request))) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); String command = "Get-AzAccessToken -ResourceUrl " + ScopeUtil.scopesToResource(request.getScopes()) + " | ConvertTo-Json"; LOGGER.verbose("Azure Powershell Authentication => Executing the command `{}` in Azure " + "Powershell to retrieve the Access Token.", command); return manager.runCommand(command) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = buildConfidentialClientParameters(request); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private SynchronizedAccessor<ConfidentialClientApplication> getConfidentialClientInstance(TokenRequestContext requestContext) { return requestContext.isCaeEnabled() ? confidentialClientApplicationAccessorWithCae : confidentialClientApplicationAccessor; } private ClientCredentialParameters.ClientCredentialParametersBuilder buildConfidentialClientParameters(TokenRequestContext request) { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder; } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } public Mono<AccessToken> authenticateWithWorkloadIdentityConfidentialClient(TokenRequestContext request) { return workloadIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = buildUsernamePasswordFlowParameters(request, username, password); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") private SynchronizedAccessor<PublicClientApplication> getPublicClientInstance(TokenRequestContext request) { return request.isCaeEnabled() ? publicClientApplicationAccessorWithCae : publicClientApplicationAccessor; } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return getPublicClientInstance(request).getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = buildDeviceCodeFlowParameters(request, deviceCodeConsumer); return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code.", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = getConfidentialClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = buildInteractiveRequestParameters(request, loginHint, redirectUri); SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); Mono<IAuthenticationResult> acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(pc::getAccounts)) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { accounts.putIfAbsent(cached.homeAccountId(), cached); } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication unavailable. " + "Multiple accounts were found in the cache. Use username and tenant id to disambiguate.") ); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; String payload = identityEndpoint + "?resource=" + urlEncode(ScopeUtil.scopesToResource(request.getScopes())) + "&api-version=" + ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION; URL url = getUrl(payload); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", "Basic " + secretKey); connection.setRequestProperty("Metadata", "true"); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> authenticateWithExchangeTokenHelper(request, assertionToken))); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(1024) .append(identityEndpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (identityHeader != null) { connection.setRequestProperty("Secret", identityHeader); } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * <p> * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(1024) .append(endpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(urlEncode(clientId)); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version=2018-02-01"); payload.append("&resource="); payload.append(urlEncode(resource)); if (clientId != null) { payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(endpoint + "?" + payload); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( "Could not connect to the url: " + url + ".", exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(ThreadLocalRandom.current().nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(endpoint + "?api-version=2018-02-01"); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return ADFS_TENANT.equals(this.tenantId); } Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider() { return appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = authenticateWithExchangeToken(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }; } }
Yeah, I'll add that in a follow up PR to TSG, as that is not shipped.
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); }
if (request.isCaeEnabled() && request.getClaims() != null) {
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); }
class IdentityClient extends IdentityClientBase { private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> workloadIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { super(tenantId, clientId, clientSecret, certificatePath, clientAssertionFilePath, resourceId, clientAssertionSupplier, certificate, certificatePassword, isSharedTokenCacheCredential, clientAssertionTimeout, options); this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, false)); this.publicClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, true)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(false)); this.confidentialClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(true)); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getManagedIdentityConfidentialClientApplication); this.workloadIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getWorkloadIdentityConfidentialClientApplication); Duration cacheTimeout = (clientAssertionTimeout == null) ? Duration.ofMinutes(5) : clientAssertionTimeout; this.clientAssertionAccessor = new SynchronizedAccessor<>(this::parseClientAssertion, cacheTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication(boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getConfidentialClient(enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getManagedIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getWorkloadIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getWorkloadIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } @Override Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential, boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getPublicClient(sharedTokenCacheCredential, enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azCommand.append(" --tenant ").append(tenant); } } catch (ClientAuthenticationException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureCLIAuthentication(azCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Developer CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureDeveloperCli(TokenRequestContext request) { StringBuilder azdCommand = new StringBuilder("azd auth token --output json --scope "); List<String> scopes = request.getScopes(); if (scopes.size() == 0) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException("Missing scope in request"))); } azdCommand.append(String.join(" --scope ", scopes)); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azdCommand.append(" --tenant-id ").append(tenant); } } catch (ClientAuthenticationException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureDeveloperCLIAuthentication(azdCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(buildOBOFlowParameters(request))) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); String command = "Get-AzAccessToken -ResourceUrl " + ScopeUtil.scopesToResource(request.getScopes()) + " | ConvertTo-Json"; LOGGER.verbose("Azure Powershell Authentication => Executing the command `{}` in Azure " + "Powershell to retrieve the Access Token.", command); return manager.runCommand(command) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = buildConfidentialClientParameters(request); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private SynchronizedAccessor<ConfidentialClientApplication> getConfidentialClientInstance(TokenRequestContext requestContext) { return requestContext.isCaeEnabled() ? confidentialClientApplicationAccessorWithCae : confidentialClientApplicationAccessor; } private ClientCredentialParameters.ClientCredentialParametersBuilder buildConfidentialClientParameters(TokenRequestContext request) { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder; } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } public Mono<AccessToken> authenticateWithWorkloadIdentityConfidentialClient(TokenRequestContext request) { return workloadIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = buildUsernamePasswordFlowParameters(request, username, password); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") private SynchronizedAccessor<PublicClientApplication> getPublicClientInstance(TokenRequestContext request) { return request.isCaeEnabled() ? publicClientApplicationAccessorWithCae : publicClientApplicationAccessor; } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return getPublicClientInstance(request).getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = buildDeviceCodeFlowParameters(request, deviceCodeConsumer); return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code.", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = getConfidentialClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = buildInteractiveRequestParameters(request, loginHint, redirectUri); SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); Mono<IAuthenticationResult> acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(pc::getAccounts)) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { accounts.putIfAbsent(cached.homeAccountId(), cached); } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication unavailable. " + "Multiple accounts were found in the cache. Use username and tenant id to disambiguate.") ); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; String payload = identityEndpoint + "?resource=" + urlEncode(ScopeUtil.scopesToResource(request.getScopes())) + "&api-version=" + ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION; URL url = getUrl(payload); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", "Basic " + secretKey); connection.setRequestProperty("Metadata", "true"); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> authenticateWithExchangeTokenHelper(request, assertionToken))); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(1024) .append(identityEndpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (identityHeader != null) { connection.setRequestProperty("Secret", identityHeader); } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * <p> * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(1024) .append(endpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(urlEncode(clientId)); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version=2018-02-01"); payload.append("&resource="); payload.append(urlEncode(resource)); if (clientId != null) { payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(endpoint + "?" + payload); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( "Could not connect to the url: " + url + ".", exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(ThreadLocalRandom.current().nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(endpoint + "?api-version=2018-02-01"); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return ADFS_TENANT.equals(this.tenantId); } Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider() { return appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = authenticateWithExchangeToken(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }; } }
class IdentityClient extends IdentityClientBase { private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> workloadIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { super(tenantId, clientId, clientSecret, certificatePath, clientAssertionFilePath, resourceId, clientAssertionSupplier, certificate, certificatePassword, isSharedTokenCacheCredential, clientAssertionTimeout, options); this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, false)); this.publicClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, true)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(false)); this.confidentialClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(true)); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getManagedIdentityConfidentialClientApplication); this.workloadIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getWorkloadIdentityConfidentialClientApplication); Duration cacheTimeout = (clientAssertionTimeout == null) ? Duration.ofMinutes(5) : clientAssertionTimeout; this.clientAssertionAccessor = new SynchronizedAccessor<>(this::parseClientAssertion, cacheTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication(boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getConfidentialClient(enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getManagedIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getWorkloadIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getWorkloadIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } @Override Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential, boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getPublicClient(sharedTokenCacheCredential, enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azCommand.append(" --tenant ").append(tenant); } } catch (ClientAuthenticationException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureCLIAuthentication(azCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Developer CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureDeveloperCli(TokenRequestContext request) { StringBuilder azdCommand = new StringBuilder("azd auth token --output json --scope "); List<String> scopes = request.getScopes(); if (scopes.size() == 0) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException("Missing scope in request"))); } azdCommand.append(String.join(" --scope ", scopes)); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azdCommand.append(" --tenant-id ").append(tenant); } } catch (ClientAuthenticationException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureDeveloperCLIAuthentication(azdCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(buildOBOFlowParameters(request))) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); String command = "Get-AzAccessToken -ResourceUrl " + ScopeUtil.scopesToResource(request.getScopes()) + " | ConvertTo-Json"; LOGGER.verbose("Azure Powershell Authentication => Executing the command `{}` in Azure " + "Powershell to retrieve the Access Token.", command); return manager.runCommand(command) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = buildConfidentialClientParameters(request); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private SynchronizedAccessor<ConfidentialClientApplication> getConfidentialClientInstance(TokenRequestContext requestContext) { return requestContext.isCaeEnabled() ? confidentialClientApplicationAccessorWithCae : confidentialClientApplicationAccessor; } private ClientCredentialParameters.ClientCredentialParametersBuilder buildConfidentialClientParameters(TokenRequestContext request) { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder; } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } public Mono<AccessToken> authenticateWithWorkloadIdentityConfidentialClient(TokenRequestContext request) { return workloadIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = buildUsernamePasswordFlowParameters(request, username, password); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") private SynchronizedAccessor<PublicClientApplication> getPublicClientInstance(TokenRequestContext request) { return request.isCaeEnabled() ? publicClientApplicationAccessorWithCae : publicClientApplicationAccessor; } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return getPublicClientInstance(request).getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = buildDeviceCodeFlowParameters(request, deviceCodeConsumer); return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code.", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = getConfidentialClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = buildInteractiveRequestParameters(request, loginHint, redirectUri); SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); Mono<IAuthenticationResult> acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(pc::getAccounts)) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { accounts.putIfAbsent(cached.homeAccountId(), cached); } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication unavailable. " + "Multiple accounts were found in the cache. Use username and tenant id to disambiguate.") ); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; String payload = identityEndpoint + "?resource=" + urlEncode(ScopeUtil.scopesToResource(request.getScopes())) + "&api-version=" + ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION; URL url = getUrl(payload); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", "Basic " + secretKey); connection.setRequestProperty("Metadata", "true"); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> authenticateWithExchangeTokenHelper(request, assertionToken))); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(1024) .append(identityEndpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (identityHeader != null) { connection.setRequestProperty("Secret", identityHeader); } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * <p> * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(1024) .append(endpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(urlEncode(clientId)); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version=2018-02-01"); payload.append("&resource="); payload.append(urlEncode(resource)); if (clientId != null) { payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(endpoint + "?" + payload); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( "Could not connect to the url: " + url + ".", exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(ThreadLocalRandom.current().nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(endpoint + "?api-version=2018-02-01"); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return ADFS_TENANT.equals(this.tenantId); } Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider() { return appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = authenticateWithExchangeToken(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }; } }
nit: the retryCountTimeout -> maybe should just call retryCount, because it captures timeout retry and also retryableWebException retry.
public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.request = request; this.isReadRequest = request.isReadOnlyRequest(); this.timeoutPolicy = HttpTimeoutPolicy.getTimeoutPolicy(request); if (this.retryContext != null) { this.retryCountTimeout = this.retryContext.getRetryCount(); } if (!isOutOfRetries()) { ResponseTimeoutAndDelays current = timeoutPolicy.getTimeoutAndDelaysList().get(this.retryCountTimeout); this.request.setResponseTimeout(current.getResponseTimeout()); this.retryDelay = current.getDelayForNextRequestInSeconds(); } this.locationEndpoint = request.requestContext.locationEndpointToRoute; }
this.retryCountTimeout = this.retryContext.getRetryCount();
public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.request = request; this.isReadRequest = request.isReadOnlyRequest(); this.timeoutPolicy = HttpTimeoutPolicy.getTimeoutPolicy(request); this.isOutOfRetries = isOutOfRetries(); if (!isOutOfRetries) { ResponseTimeoutAndDelays current = timeoutPolicy.getTimeoutAndDelaysList().get(this.retryCount); this.request.setResponseTimeout(current.getResponseTimeout()); this.retryDelay = current.getDelayForNextRequestInSeconds(); } this.retryCount++; this.locationEndpoint = request.requestContext.locationEndpointToRoute; }
class WebExceptionRetryPolicy implements IRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(WebExceptionRetryPolicy.class); private StopWatch durationTimer = new StopWatch(); private RetryContext retryContext; private int retryDelay; private RxDocumentServiceRequest request; private HttpTimeoutPolicy timeoutPolicy; private boolean isReadRequest; private int retryCountTimeout = 0; private URI locationEndpoint; public WebExceptionRetryPolicy() { durationTimer.start(); } public WebExceptionRetryPolicy(RetryContext retryContext) { durationTimer.start(); this.retryContext = retryContext; this.timeoutPolicy = HttpTimeoutPolicyDefault.INSTANCE; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception e) { boolean isOutOfRetries = isOutOfRetries(); if (isOutOfRetries) { this.durationTimer.stop(); return Mono.just(ShouldRetryResult.noRetry()); } CosmosException webException = Utils.as(e, CosmosException.class); if (WebExceptionUtility.isNetworkFailure(e) && this.isReadRequest && (webException != null && WebExceptionUtility.isReadTimeoutException(webException) && Exceptions.isSubStatusCode(webException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT))) { if (this.request.isAddressRefresh()) { return shouldRetryAddressRefresh(); } return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } if (!WebExceptionUtility.isWebExceptionRetriable(e)) { this.durationTimer.stop(); return Mono.just(ShouldRetryResult.noRetryOnNonRelatedException()); } logger.warn("Received retriable web exception, will retry", e); return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } @Override public RetryContext getRetryContext() { return this.retryContext; } private Boolean isOutOfRetries() { return this.retryCountTimeout >= this.timeoutPolicy.totalRetryCount(); } private Mono<ShouldRetryResult> shouldRetryAddressRefresh() { logger .warn("shouldRetryAddressRefresh() Retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}, shouldForcedAddressRefresh = {}, " + "shouldForceCollectionRoutingMapRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.retryCountTimeout, this.request.isAddressRefresh(), this.request.shouldForceAddressRefresh(), this.request.forceCollectionRoutingMapRefresh); return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } }
class WebExceptionRetryPolicy implements IRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(WebExceptionRetryPolicy.class); private StopWatch durationTimer = new StopWatch(); private RetryContext retryContext; private int retryDelay; private RxDocumentServiceRequest request; private HttpTimeoutPolicy timeoutPolicy; private boolean isReadRequest; private int retryCount = 0; private URI locationEndpoint; private boolean isOutOfRetries; public WebExceptionRetryPolicy() { durationTimer.start(); } public WebExceptionRetryPolicy(RetryContext retryContext) { durationTimer.start(); this.retryContext = retryContext; this.timeoutPolicy = HttpTimeoutPolicyDefault.INSTANCE; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception e) { if (isOutOfRetries) { this.durationTimer.stop(); return Mono.just(ShouldRetryResult.noRetry()); } CosmosException webException = Utils.as(e, CosmosException.class); if (WebExceptionUtility.isNetworkFailure(e) && this.isReadRequest && (webException != null && WebExceptionUtility.isReadTimeoutException(webException) && Exceptions.isSubStatusCode(webException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT))) { if (this.request.isAddressRefresh()) { return shouldRetryAddressRefresh(); } return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } if (!WebExceptionUtility.isWebExceptionRetriable(e)) { this.durationTimer.stop(); return Mono.just(ShouldRetryResult.noRetryOnNonRelatedException()); } logger.warn("Received retriable web exception, will retry", e); return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } @Override public RetryContext getRetryContext() { return this.retryContext; } private boolean isOutOfRetries() { return this.retryCount >= this.timeoutPolicy.totalRetryCount(); } private Mono<ShouldRetryResult> shouldRetryAddressRefresh() { if (isOutOfRetries) { logger .warn( "shouldRetryAddressRefresh() No more retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.retryCount, this.request.isAddressRefresh()); return Mono.just(ShouldRetryResult.noRetry()); } logger .warn("shouldRetryAddressRefresh() Retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}, shouldForcedAddressRefresh = {}, " + "shouldForceCollectionRoutingMapRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.retryCount, this.request.isAddressRefresh(), this.request.shouldForceAddressRefresh(), this.request.forceCollectionRoutingMapRefresh); return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } }
why do we need this?
public void setupTest(TestInfo testInfo) { Assumptions.assumeFalse(getTestMode() == TestMode.PLAYBACK, "Skipping playback tests"); super.setupTest(testInfo); }
super.setupTest(testInfo);
public void setupTest(TestInfo testInfo) { Assumptions.assumeFalse(getTestMode() == TestMode.PLAYBACK, "Skipping playback tests"); super.setupTest(testInfo); }
class AppConfigurationExporterIntegrationTest extends MonitorExporterClientTestBase { @Override @BeforeEach @Override @AfterEach public void teardownTest(TestInfo testInfo) { GlobalOpenTelemetry.resetForTest(); } @Test public void setConfigurationTest() throws InterruptedException { CountDownLatch appConfigCountDown = new CountDownLatch(1); CountDownLatch exporterCountDown = new CountDownLatch(1); ValidationPolicy validationPolicy = new ValidationPolicy(exporterCountDown, "AppConfig.setKey"); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk(getHttpPipeline(validationPolicy)); Tracer tracer = openTelemetry.getTracer("Sample"); ConfigurationClient client = getConfigurationClient(appConfigCountDown); Span span = tracer.spanBuilder("set-config-exporter-testing").startSpan(); Scope scope = span.makeCurrent(); try { client.setConfigurationSetting("hello", "text", "World"); } finally { span.end(); scope.close(); } assertTrue(appConfigCountDown.await(60, TimeUnit.SECONDS)); assertTrue(exporterCountDown.await(60, TimeUnit.SECONDS)); } @Disabled( "Multiple tests fail to trigger end span - https: @Test public void testDisableTracing() throws InterruptedException { CountDownLatch appConfigCountDown = new CountDownLatch(1); CountDownLatch exporterCountDown = new CountDownLatch(1); ValidationPolicy validationPolicy = new ValidationPolicy(exporterCountDown, "disable-config-exporter-testing"); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk(getHttpPipeline(validationPolicy)); Tracer tracer = openTelemetry.getTracer("Sample"); ConfigurationClient client = getConfigurationClient(appConfigCountDown); Span span = tracer.spanBuilder("disable-config-exporter-testing").startSpan(); Scope scope = span.makeCurrent(); try { ConfigurationSetting configurationSetting = new ConfigurationSetting().setKey("hello").setLabel("text").setValue("World"); client.setConfigurationSettingWithResponse( configurationSetting, false, Context.NONE.addData(DISABLE_TRACING_KEY, true)); } finally { span.end(); scope.close(); } assertTrue(appConfigCountDown.await(60, TimeUnit.SECONDS)); assertTrue(exporterCountDown.await(60, TimeUnit.SECONDS)); } private static ConfigurationClient getConfigurationClient(CountDownLatch appConfigCountDown) { return new ConfigurationClientBuilder() .connectionString(System.getenv("AZURE_APPCONFIG_CONNECTION_STRING")) .addPolicy( (context, next) -> { Optional<Object> data = context.getData(com.azure.core.util.tracing.Tracer.AZ_TRACING_NAMESPACE_KEY); if (data.isPresent() && data.get().equals("Microsoft.AppConfiguration")) { appConfigCountDown.countDown(); } return next.process(); }) .buildClient(); } static class ValidationPolicy implements HttpPipelinePolicy { private final CountDownLatch countDown; private final String expectedSpanName; ValidationPolicy(CountDownLatch countDown, String expectedSpanName) { this.countDown = countDown; this.expectedSpanName = expectedSpanName; } @Override public Mono<HttpResponse> process( HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Mono<String> asyncString = FluxUtil.collectBytesInByteBufferStream(context.getHttpRequest().getBody()) .map(bytes -> new String(bytes, StandardCharsets.UTF_8)); asyncString.subscribe( value -> { if (value.contains(expectedSpanName)) { countDown.countDown(); } }); return next.process(); } } }
class AppConfigurationExporterIntegrationTest extends MonitorExporterClientTestBase { @Override @BeforeEach @Override @AfterEach public void teardownTest(TestInfo testInfo) { GlobalOpenTelemetry.resetForTest(); } @Test public void setConfigurationTest() throws InterruptedException { CountDownLatch exporterCountDown = new CountDownLatch(1); ValidationPolicy validationPolicy = new ValidationPolicy(exporterCountDown, "set-config-exporter-testing"); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk(getHttpPipeline(validationPolicy)); Tracer tracer = openTelemetry.getTracer("Sample"); ConfigurationClient client = getConfigurationClient(); Span span = tracer.spanBuilder("set-config-exporter-testing").startSpan(); Scope scope = span.makeCurrent(); try { client.setConfigurationSetting("hello", "text", "World"); } finally { span.end(); scope.close(); } assertTrue(exporterCountDown.await(60, TimeUnit.SECONDS)); } @Disabled( "Multiple tests fail to trigger end span - https: @Test public void testDisableTracing() throws InterruptedException { CountDownLatch exporterCountDown = new CountDownLatch(1); ValidationPolicy validationPolicy = new ValidationPolicy(exporterCountDown, "disable-config-exporter-testing"); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk(getHttpPipeline(validationPolicy)); Tracer tracer = openTelemetry.getTracer("Sample"); ConfigurationClient client = getConfigurationClient(); Span span = tracer.spanBuilder("disable-config-exporter-testing").startSpan(); Scope scope = span.makeCurrent(); try { ConfigurationSetting configurationSetting = new ConfigurationSetting().setKey("hello").setLabel("text").setValue("World"); client.setConfigurationSettingWithResponse( configurationSetting, false, Context.NONE.addData(DISABLE_TRACING_KEY, true)); } finally { span.end(); scope.close(); } assertTrue(exporterCountDown.await(60, TimeUnit.SECONDS)); } private static ConfigurationClient getConfigurationClient() { return new ConfigurationClientBuilder() .connectionString(System.getenv("AZURE_APPCONFIG_CONNECTION_STRING")) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .buildClient(); } static class ValidationPolicy implements HttpPipelinePolicy { private final CountDownLatch countDown; private final String expectedSpanName; ValidationPolicy(CountDownLatch countDown, String expectedSpanName) { this.countDown = countDown; this.expectedSpanName = expectedSpanName; } @Override public Mono<HttpResponse> process( HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Mono<String> asyncString = FluxUtil.collectBytesInByteBufferStream(context.getHttpRequest().getBody()) .map(bytes -> ungzip(bytes)) .map(bytes -> new String(bytes, StandardCharsets.UTF_8)); asyncString.subscribe( value -> { if (value.contains(expectedSpanName)) { countDown.countDown(); } }); return next.process(); } private static byte[] ungzip(byte[] bytes) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes))) { byte[] buffer = new byte[1024]; int len; while ((len = gis.read(buffer)) > 0) { bos.write(buffer, 0, len); } } catch (IOException e) { throw new RuntimeException(e); } return bos.toByteArray(); } } }
This is needed for the setup to be done (i.e. call the setupTest method of the base class) when the test mode is not PLAYBACK.
public void setupTest(TestInfo testInfo) { Assumptions.assumeFalse(getTestMode() == TestMode.PLAYBACK, "Skipping playback tests"); super.setupTest(testInfo); }
super.setupTest(testInfo);
public void setupTest(TestInfo testInfo) { Assumptions.assumeFalse(getTestMode() == TestMode.PLAYBACK, "Skipping playback tests"); super.setupTest(testInfo); }
class AppConfigurationExporterIntegrationTest extends MonitorExporterClientTestBase { @Override @BeforeEach @Override @AfterEach public void teardownTest(TestInfo testInfo) { GlobalOpenTelemetry.resetForTest(); } @Test public void setConfigurationTest() throws InterruptedException { CountDownLatch appConfigCountDown = new CountDownLatch(1); CountDownLatch exporterCountDown = new CountDownLatch(1); ValidationPolicy validationPolicy = new ValidationPolicy(exporterCountDown, "AppConfig.setKey"); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk(getHttpPipeline(validationPolicy)); Tracer tracer = openTelemetry.getTracer("Sample"); ConfigurationClient client = getConfigurationClient(appConfigCountDown); Span span = tracer.spanBuilder("set-config-exporter-testing").startSpan(); Scope scope = span.makeCurrent(); try { client.setConfigurationSetting("hello", "text", "World"); } finally { span.end(); scope.close(); } assertTrue(appConfigCountDown.await(60, TimeUnit.SECONDS)); assertTrue(exporterCountDown.await(60, TimeUnit.SECONDS)); } @Disabled( "Multiple tests fail to trigger end span - https: @Test public void testDisableTracing() throws InterruptedException { CountDownLatch appConfigCountDown = new CountDownLatch(1); CountDownLatch exporterCountDown = new CountDownLatch(1); ValidationPolicy validationPolicy = new ValidationPolicy(exporterCountDown, "disable-config-exporter-testing"); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk(getHttpPipeline(validationPolicy)); Tracer tracer = openTelemetry.getTracer("Sample"); ConfigurationClient client = getConfigurationClient(appConfigCountDown); Span span = tracer.spanBuilder("disable-config-exporter-testing").startSpan(); Scope scope = span.makeCurrent(); try { ConfigurationSetting configurationSetting = new ConfigurationSetting().setKey("hello").setLabel("text").setValue("World"); client.setConfigurationSettingWithResponse( configurationSetting, false, Context.NONE.addData(DISABLE_TRACING_KEY, true)); } finally { span.end(); scope.close(); } assertTrue(appConfigCountDown.await(60, TimeUnit.SECONDS)); assertTrue(exporterCountDown.await(60, TimeUnit.SECONDS)); } private static ConfigurationClient getConfigurationClient(CountDownLatch appConfigCountDown) { return new ConfigurationClientBuilder() .connectionString(System.getenv("AZURE_APPCONFIG_CONNECTION_STRING")) .addPolicy( (context, next) -> { Optional<Object> data = context.getData(com.azure.core.util.tracing.Tracer.AZ_TRACING_NAMESPACE_KEY); if (data.isPresent() && data.get().equals("Microsoft.AppConfiguration")) { appConfigCountDown.countDown(); } return next.process(); }) .buildClient(); } static class ValidationPolicy implements HttpPipelinePolicy { private final CountDownLatch countDown; private final String expectedSpanName; ValidationPolicy(CountDownLatch countDown, String expectedSpanName) { this.countDown = countDown; this.expectedSpanName = expectedSpanName; } @Override public Mono<HttpResponse> process( HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Mono<String> asyncString = FluxUtil.collectBytesInByteBufferStream(context.getHttpRequest().getBody()) .map(bytes -> new String(bytes, StandardCharsets.UTF_8)); asyncString.subscribe( value -> { if (value.contains(expectedSpanName)) { countDown.countDown(); } }); return next.process(); } } }
class AppConfigurationExporterIntegrationTest extends MonitorExporterClientTestBase { @Override @BeforeEach @Override @AfterEach public void teardownTest(TestInfo testInfo) { GlobalOpenTelemetry.resetForTest(); } @Test public void setConfigurationTest() throws InterruptedException { CountDownLatch exporterCountDown = new CountDownLatch(1); ValidationPolicy validationPolicy = new ValidationPolicy(exporterCountDown, "set-config-exporter-testing"); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk(getHttpPipeline(validationPolicy)); Tracer tracer = openTelemetry.getTracer("Sample"); ConfigurationClient client = getConfigurationClient(); Span span = tracer.spanBuilder("set-config-exporter-testing").startSpan(); Scope scope = span.makeCurrent(); try { client.setConfigurationSetting("hello", "text", "World"); } finally { span.end(); scope.close(); } assertTrue(exporterCountDown.await(60, TimeUnit.SECONDS)); } @Disabled( "Multiple tests fail to trigger end span - https: @Test public void testDisableTracing() throws InterruptedException { CountDownLatch exporterCountDown = new CountDownLatch(1); ValidationPolicy validationPolicy = new ValidationPolicy(exporterCountDown, "disable-config-exporter-testing"); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk(getHttpPipeline(validationPolicy)); Tracer tracer = openTelemetry.getTracer("Sample"); ConfigurationClient client = getConfigurationClient(); Span span = tracer.spanBuilder("disable-config-exporter-testing").startSpan(); Scope scope = span.makeCurrent(); try { ConfigurationSetting configurationSetting = new ConfigurationSetting().setKey("hello").setLabel("text").setValue("World"); client.setConfigurationSettingWithResponse( configurationSetting, false, Context.NONE.addData(DISABLE_TRACING_KEY, true)); } finally { span.end(); scope.close(); } assertTrue(exporterCountDown.await(60, TimeUnit.SECONDS)); } private static ConfigurationClient getConfigurationClient() { return new ConfigurationClientBuilder() .connectionString(System.getenv("AZURE_APPCONFIG_CONNECTION_STRING")) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .buildClient(); } static class ValidationPolicy implements HttpPipelinePolicy { private final CountDownLatch countDown; private final String expectedSpanName; ValidationPolicy(CountDownLatch countDown, String expectedSpanName) { this.countDown = countDown; this.expectedSpanName = expectedSpanName; } @Override public Mono<HttpResponse> process( HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Mono<String> asyncString = FluxUtil.collectBytesInByteBufferStream(context.getHttpRequest().getBody()) .map(bytes -> ungzip(bytes)) .map(bytes -> new String(bytes, StandardCharsets.UTF_8)); asyncString.subscribe( value -> { if (value.contains(expectedSpanName)) { countDown.countDown(); } }); return next.process(); } private static byte[] ungzip(byte[] bytes) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes))) { byte[] buffer = new byte[1024]; int len; while ((len = gis.read(buffer)) > 0) { bos.write(buffer, 0, len); } } catch (IOException e) { throw new RuntimeException(e); } return bos.toByteArray(); } } }
nit: `backOfTime` -> `backOffTime`
public void shouldRetryOnTimeoutForReadOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/doc", ResourceType.Document); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); }
backOfTime(Duration.ofSeconds(0)).
public void shouldRetryOnTimeoutForReadOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/doc", ResourceType.Document); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); }
class WebExceptionRetryPolicyTest extends TestSuiteBase { @Test(groups = {"unit"}) @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForMetaDataReadOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/doc", ResourceType.DatabaseAccount); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(5)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(10)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(20)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); } @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForQueryPlanOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.QueryPlan, "/dbs/db/colls/col/docs/doc", ResourceType.Document); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofMillis(500)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(5)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(10)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); } @Test(groups = "unit") public void shouldNotRetryOnTimeoutForWriteOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Create, "/dbs/db/colls/col/docs/doc", ResourceType.Document); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(new RetryContext()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Create, "/dbs/db/colls/col/docs/docId", ResourceType.Database); webExceptionRetryPolicy = new WebExceptionRetryPolicy(new RetryContext()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); } @Test(groups = "unit") public void httpNetworkFailureOnAddressRefresh() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(false)); Mockito.doReturn(2).when(endpointManager).getPreferredLocationCount(); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/", ResourceType.Document); dsr.setAddressRefresh(true, false); dsr.requestContext = new DocumentServiceRequestContext(); webExceptionRetryPolicy.onBeforeSendRequest(dsr); for (int i = 0; i < 10; i++) { Mono<ShouldRetryResult> shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); if (i < 3) { validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(true) .backOfTime(Duration.ofMillis(0)) .build()); } else { validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); } Mockito.verify(endpointManager, Mockito.times(0)).markEndpointUnavailableForRead(Mockito.any()); Mockito.verify(endpointManager, Mockito.times(0)).markEndpointUnavailableForWrite(Mockito.any()); } } public static void validateSuccess(Mono<ShouldRetryResult> single, ShouldRetryValidator validator) { validateSuccess(single, validator, TIMEOUT); } public static void validateSuccess(Mono<ShouldRetryResult> single, ShouldRetryValidator validator, long timeout) { TestSubscriber<ShouldRetryResult> testSubscriber = new TestSubscriber<>(); single.flux().subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertComplete(); testSubscriber.assertNoErrors(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } }
class WebExceptionRetryPolicyTest extends TestSuiteBase { @Test(groups = {"unit"}) @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForMetaDataReadOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/doc", ResourceType.DatabaseAccount); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(5)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(10)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(20)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); } @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForQueryPlanOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.QueryPlan, "/dbs/db/colls/col/docs/doc", ResourceType.Document); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofMillis(500)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(5)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(10)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); } @Test(groups = "unit") public void shouldNotRetryOnTimeoutForWriteOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Create, "/dbs/db/colls/col/docs/doc", ResourceType.Document); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(new RetryContext()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Create, "/dbs/db/colls/col/docs/docId", ResourceType.Database); webExceptionRetryPolicy = new WebExceptionRetryPolicy(new RetryContext()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); } @Test(groups = "unit") public void httpNetworkFailureOnAddressRefresh() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(false)); Mockito.doReturn(2).when(endpointManager).getPreferredLocationCount(); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/", ResourceType.Document); dsr.setAddressRefresh(true, false); dsr.requestContext = new DocumentServiceRequestContext(); webExceptionRetryPolicy.onBeforeSendRequest(dsr); Mono<ShouldRetryResult> shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofMillis(500)); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(true) .backOffTime(Duration.ofSeconds(0)) .build()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(5)); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(true) .backOffTime(Duration.ofSeconds(1)) .build()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(10)); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(true) .backOffTime(Duration.ofSeconds(0)) .build()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); } public static void validateSuccess(Mono<ShouldRetryResult> single, ShouldRetryValidator validator) { validateSuccess(single, validator, TIMEOUT); } public static void validateSuccess(Mono<ShouldRetryResult> single, ShouldRetryValidator validator, long timeout) { TestSubscriber<ShouldRetryResult> testSubscriber = new TestSubscriber<>(); single.flux().subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertComplete(); testSubscriber.assertNoErrors(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } }
what about the response timeout value validation? and also for address refresh, there is no backoff time differences between the retries?
public void httpNetworkFailureOnAddressRefresh() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(false)); Mockito.doReturn(2).when(endpointManager).getPreferredLocationCount(); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/", ResourceType.Document); dsr.setAddressRefresh(true, false); dsr.requestContext = new DocumentServiceRequestContext(); webExceptionRetryPolicy.onBeforeSendRequest(dsr); for (int i = 0; i < 10; i++) { Mono<ShouldRetryResult> shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); if (i < 3) { validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(true) .backOfTime(Duration.ofMillis(0)) .build()); } else { validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); } Mockito.verify(endpointManager, Mockito.times(0)).markEndpointUnavailableForRead(Mockito.any()); Mockito.verify(endpointManager, Mockito.times(0)).markEndpointUnavailableForWrite(Mockito.any()); } }
Mono<ShouldRetryResult> shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException);
public void httpNetworkFailureOnAddressRefresh() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(false)); Mockito.doReturn(2).when(endpointManager).getPreferredLocationCount(); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/", ResourceType.Document); dsr.setAddressRefresh(true, false); dsr.requestContext = new DocumentServiceRequestContext(); webExceptionRetryPolicy.onBeforeSendRequest(dsr); Mono<ShouldRetryResult> shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofMillis(500)); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(true) .backOffTime(Duration.ofSeconds(0)) .build()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(5)); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(true) .backOffTime(Duration.ofSeconds(1)) .build()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(10)); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(true) .backOffTime(Duration.ofSeconds(0)) .build()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); }
class WebExceptionRetryPolicyTest extends TestSuiteBase { @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForReadOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/doc", ResourceType.Document); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); } @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForMetaDataReadOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/doc", ResourceType.DatabaseAccount); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(5)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(10)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(20)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); } @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForQueryPlanOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.QueryPlan, "/dbs/db/colls/col/docs/doc", ResourceType.Document); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofMillis(500)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(5)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(10)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); } @Test(groups = "unit") public void shouldNotRetryOnTimeoutForWriteOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Create, "/dbs/db/colls/col/docs/doc", ResourceType.Document); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(new RetryContext()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Create, "/dbs/db/colls/col/docs/docId", ResourceType.Database); webExceptionRetryPolicy = new WebExceptionRetryPolicy(new RetryContext()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); } @Test(groups = "unit") public static void validateSuccess(Mono<ShouldRetryResult> single, ShouldRetryValidator validator) { validateSuccess(single, validator, TIMEOUT); } public static void validateSuccess(Mono<ShouldRetryResult> single, ShouldRetryValidator validator, long timeout) { TestSubscriber<ShouldRetryResult> testSubscriber = new TestSubscriber<>(); single.flux().subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertComplete(); testSubscriber.assertNoErrors(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } }
class WebExceptionRetryPolicyTest extends TestSuiteBase { @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForReadOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/doc", ResourceType.Document); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); } @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForMetaDataReadOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/doc", ResourceType.DatabaseAccount); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(5)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(10)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(20)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); } @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForQueryPlanOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.QueryPlan, "/dbs/db/colls/col/docs/doc", ResourceType.Document); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofMillis(500)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(5)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(10)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); } @Test(groups = "unit") public void shouldNotRetryOnTimeoutForWriteOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Create, "/dbs/db/colls/col/docs/doc", ResourceType.Document); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(new RetryContext()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Create, "/dbs/db/colls/col/docs/docId", ResourceType.Database); webExceptionRetryPolicy = new WebExceptionRetryPolicy(new RetryContext()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); } @Test(groups = "unit") public static void validateSuccess(Mono<ShouldRetryResult> single, ShouldRetryValidator validator) { validateSuccess(single, validator, TIMEOUT); } public static void validateSuccess(Mono<ShouldRetryResult> single, ShouldRetryValidator validator, long timeout) { TestSubscriber<ShouldRetryResult> testSubscriber = new TestSubscriber<>(); single.flux().subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertComplete(); testSubscriber.assertNoErrors(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } }
There is no increase of `retryCountTimeout`?
public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.request = request; this.isReadRequest = request.isReadOnlyRequest(); this.timeoutPolicy = HttpTimeoutPolicy.getTimeoutPolicy(request); if (this.retryContext != null) { this.retryCountTimeout = this.retryContext.getRetryCount(); } if (!isOutOfRetries()) { ResponseTimeoutAndDelays current = timeoutPolicy.getTimeoutAndDelaysList().get(this.retryCountTimeout); this.request.setResponseTimeout(current.getResponseTimeout()); this.retryDelay = current.getDelayForNextRequestInSeconds(); } this.locationEndpoint = request.requestContext.locationEndpointToRoute; }
this.retryCountTimeout = this.retryContext.getRetryCount();
public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.request = request; this.isReadRequest = request.isReadOnlyRequest(); this.timeoutPolicy = HttpTimeoutPolicy.getTimeoutPolicy(request); this.isOutOfRetries = isOutOfRetries(); if (!isOutOfRetries) { ResponseTimeoutAndDelays current = timeoutPolicy.getTimeoutAndDelaysList().get(this.retryCount); this.request.setResponseTimeout(current.getResponseTimeout()); this.retryDelay = current.getDelayForNextRequestInSeconds(); } this.retryCount++; this.locationEndpoint = request.requestContext.locationEndpointToRoute; }
class WebExceptionRetryPolicy implements IRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(WebExceptionRetryPolicy.class); private StopWatch durationTimer = new StopWatch(); private RetryContext retryContext; private int retryDelay; private RxDocumentServiceRequest request; private HttpTimeoutPolicy timeoutPolicy; private boolean isReadRequest; private int retryCountTimeout = 0; private URI locationEndpoint; public WebExceptionRetryPolicy() { durationTimer.start(); } public WebExceptionRetryPolicy(RetryContext retryContext) { durationTimer.start(); this.retryContext = retryContext; this.timeoutPolicy = HttpTimeoutPolicyDefault.INSTANCE; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception e) { boolean isOutOfRetries = isOutOfRetries(); if (isOutOfRetries) { this.durationTimer.stop(); return Mono.just(ShouldRetryResult.noRetry()); } CosmosException webException = Utils.as(e, CosmosException.class); if (WebExceptionUtility.isNetworkFailure(e) && this.isReadRequest && (webException != null && WebExceptionUtility.isReadTimeoutException(webException) && Exceptions.isSubStatusCode(webException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT))) { if (this.request.isAddressRefresh()) { return shouldRetryAddressRefresh(); } return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } if (!WebExceptionUtility.isWebExceptionRetriable(e)) { this.durationTimer.stop(); return Mono.just(ShouldRetryResult.noRetryOnNonRelatedException()); } logger.warn("Received retriable web exception, will retry", e); return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } @Override public RetryContext getRetryContext() { return this.retryContext; } private Boolean isOutOfRetries() { return this.retryCountTimeout >= this.timeoutPolicy.totalRetryCount(); } private Mono<ShouldRetryResult> shouldRetryAddressRefresh() { logger .warn("shouldRetryAddressRefresh() Retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}, shouldForcedAddressRefresh = {}, " + "shouldForceCollectionRoutingMapRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.retryCountTimeout, this.request.isAddressRefresh(), this.request.shouldForceAddressRefresh(), this.request.forceCollectionRoutingMapRefresh); return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } }
class WebExceptionRetryPolicy implements IRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(WebExceptionRetryPolicy.class); private StopWatch durationTimer = new StopWatch(); private RetryContext retryContext; private int retryDelay; private RxDocumentServiceRequest request; private HttpTimeoutPolicy timeoutPolicy; private boolean isReadRequest; private int retryCount = 0; private URI locationEndpoint; private boolean isOutOfRetries; public WebExceptionRetryPolicy() { durationTimer.start(); } public WebExceptionRetryPolicy(RetryContext retryContext) { durationTimer.start(); this.retryContext = retryContext; this.timeoutPolicy = HttpTimeoutPolicyDefault.INSTANCE; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception e) { if (isOutOfRetries) { this.durationTimer.stop(); return Mono.just(ShouldRetryResult.noRetry()); } CosmosException webException = Utils.as(e, CosmosException.class); if (WebExceptionUtility.isNetworkFailure(e) && this.isReadRequest && (webException != null && WebExceptionUtility.isReadTimeoutException(webException) && Exceptions.isSubStatusCode(webException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT))) { if (this.request.isAddressRefresh()) { return shouldRetryAddressRefresh(); } return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } if (!WebExceptionUtility.isWebExceptionRetriable(e)) { this.durationTimer.stop(); return Mono.just(ShouldRetryResult.noRetryOnNonRelatedException()); } logger.warn("Received retriable web exception, will retry", e); return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } @Override public RetryContext getRetryContext() { return this.retryContext; } private boolean isOutOfRetries() { return this.retryCount >= this.timeoutPolicy.totalRetryCount(); } private Mono<ShouldRetryResult> shouldRetryAddressRefresh() { if (isOutOfRetries) { logger .warn( "shouldRetryAddressRefresh() No more retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.retryCount, this.request.isAddressRefresh()); return Mono.just(ShouldRetryResult.noRetry()); } logger .warn("shouldRetryAddressRefresh() Retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}, shouldForcedAddressRefresh = {}, " + "shouldForceCollectionRoutingMapRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.retryCount, this.request.isAddressRefresh(), this.request.shouldForceAddressRefresh(), this.request.forceCollectionRoutingMapRefresh); return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } }
Fixed the test case
public void httpNetworkFailureOnAddressRefresh() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(false)); Mockito.doReturn(2).when(endpointManager).getPreferredLocationCount(); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/", ResourceType.Document); dsr.setAddressRefresh(true, false); dsr.requestContext = new DocumentServiceRequestContext(); webExceptionRetryPolicy.onBeforeSendRequest(dsr); for (int i = 0; i < 10; i++) { Mono<ShouldRetryResult> shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); if (i < 3) { validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(true) .backOfTime(Duration.ofMillis(0)) .build()); } else { validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); } Mockito.verify(endpointManager, Mockito.times(0)).markEndpointUnavailableForRead(Mockito.any()); Mockito.verify(endpointManager, Mockito.times(0)).markEndpointUnavailableForWrite(Mockito.any()); } }
Mono<ShouldRetryResult> shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException);
public void httpNetworkFailureOnAddressRefresh() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(false)); Mockito.doReturn(2).when(endpointManager).getPreferredLocationCount(); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/", ResourceType.Document); dsr.setAddressRefresh(true, false); dsr.requestContext = new DocumentServiceRequestContext(); webExceptionRetryPolicy.onBeforeSendRequest(dsr); Mono<ShouldRetryResult> shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofMillis(500)); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(true) .backOffTime(Duration.ofSeconds(0)) .build()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(5)); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(true) .backOffTime(Duration.ofSeconds(1)) .build()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(10)); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(true) .backOffTime(Duration.ofSeconds(0)) .build()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); }
class WebExceptionRetryPolicyTest extends TestSuiteBase { @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForReadOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/doc", ResourceType.Document); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); } @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForMetaDataReadOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/doc", ResourceType.DatabaseAccount); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(5)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(10)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(20)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); } @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForQueryPlanOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.QueryPlan, "/dbs/db/colls/col/docs/doc", ResourceType.Document); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofMillis(500)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(5)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(10)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOfTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); } @Test(groups = "unit") public void shouldNotRetryOnTimeoutForWriteOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Create, "/dbs/db/colls/col/docs/doc", ResourceType.Document); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(new RetryContext()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Create, "/dbs/db/colls/col/docs/docId", ResourceType.Database); webExceptionRetryPolicy = new WebExceptionRetryPolicy(new RetryContext()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); } @Test(groups = "unit") public static void validateSuccess(Mono<ShouldRetryResult> single, ShouldRetryValidator validator) { validateSuccess(single, validator, TIMEOUT); } public static void validateSuccess(Mono<ShouldRetryResult> single, ShouldRetryValidator validator, long timeout) { TestSubscriber<ShouldRetryResult> testSubscriber = new TestSubscriber<>(); single.flux().subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertComplete(); testSubscriber.assertNoErrors(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } }
class WebExceptionRetryPolicyTest extends TestSuiteBase { @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForReadOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/doc", ResourceType.Document); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(60)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); } @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForMetaDataReadOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/doc", ResourceType.DatabaseAccount); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(5)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(10)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(20)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); } @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForQueryPlanOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(retryContext); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.QueryPlan, "/dbs/db/colls/col/docs/doc", ResourceType.Document); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofMillis(500)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(5)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(1)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); assertThat(dsr.getResponseTimeout()).isEqualTo(Duration.ofSeconds(10)); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(true). backOffTime(Duration.ofSeconds(0)). build()); retryContext.addStatusAndSubStatusCode(408, 10002); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder(). nullException(). shouldRetry(false). build()); } @Test(groups = "unit") public void shouldNotRetryOnTimeoutForWriteOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URI("http: Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); Exception exception = ReadTimeoutException.INSTANCE; CosmosException cosmosException = BridgeInternal.createCosmosException(null, HttpConstants.StatusCodes.REQUEST_TIMEOUT, exception); BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); RxDocumentServiceRequest dsr; Mono<ShouldRetryResult> shouldRetry; dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Create, "/dbs/db/colls/col/docs/doc", ResourceType.Document); WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(new RetryContext()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Create, "/dbs/db/colls/col/docs/docId", ResourceType.Database); webExceptionRetryPolicy = new WebExceptionRetryPolicy(new RetryContext()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); shouldRetry = webExceptionRetryPolicy.shouldRetry(cosmosException); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(false) .build()); } @Test(groups = "unit") public static void validateSuccess(Mono<ShouldRetryResult> single, ShouldRetryValidator validator) { validateSuccess(single, validator, TIMEOUT); } public static void validateSuccess(Mono<ShouldRetryResult> single, ShouldRetryValidator validator, long timeout) { TestSubscriber<ShouldRetryResult> testSubscriber = new TestSubscriber<>(); single.flux().subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertComplete(); testSubscriber.assertNoErrors(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } }
Done.
public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.request = request; this.isReadRequest = request.isReadOnlyRequest(); this.timeoutPolicy = HttpTimeoutPolicy.getTimeoutPolicy(request); if (this.retryContext != null) { this.retryCountTimeout = this.retryContext.getRetryCount(); } if (!isOutOfRetries()) { ResponseTimeoutAndDelays current = timeoutPolicy.getTimeoutAndDelaysList().get(this.retryCountTimeout); this.request.setResponseTimeout(current.getResponseTimeout()); this.retryDelay = current.getDelayForNextRequestInSeconds(); } this.locationEndpoint = request.requestContext.locationEndpointToRoute; }
this.retryCountTimeout = this.retryContext.getRetryCount();
public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.request = request; this.isReadRequest = request.isReadOnlyRequest(); this.timeoutPolicy = HttpTimeoutPolicy.getTimeoutPolicy(request); this.isOutOfRetries = isOutOfRetries(); if (!isOutOfRetries) { ResponseTimeoutAndDelays current = timeoutPolicy.getTimeoutAndDelaysList().get(this.retryCount); this.request.setResponseTimeout(current.getResponseTimeout()); this.retryDelay = current.getDelayForNextRequestInSeconds(); } this.retryCount++; this.locationEndpoint = request.requestContext.locationEndpointToRoute; }
class WebExceptionRetryPolicy implements IRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(WebExceptionRetryPolicy.class); private StopWatch durationTimer = new StopWatch(); private RetryContext retryContext; private int retryDelay; private RxDocumentServiceRequest request; private HttpTimeoutPolicy timeoutPolicy; private boolean isReadRequest; private int retryCountTimeout = 0; private URI locationEndpoint; public WebExceptionRetryPolicy() { durationTimer.start(); } public WebExceptionRetryPolicy(RetryContext retryContext) { durationTimer.start(); this.retryContext = retryContext; this.timeoutPolicy = HttpTimeoutPolicyDefault.INSTANCE; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception e) { boolean isOutOfRetries = isOutOfRetries(); if (isOutOfRetries) { this.durationTimer.stop(); return Mono.just(ShouldRetryResult.noRetry()); } CosmosException webException = Utils.as(e, CosmosException.class); if (WebExceptionUtility.isNetworkFailure(e) && this.isReadRequest && (webException != null && WebExceptionUtility.isReadTimeoutException(webException) && Exceptions.isSubStatusCode(webException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT))) { if (this.request.isAddressRefresh()) { return shouldRetryAddressRefresh(); } return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } if (!WebExceptionUtility.isWebExceptionRetriable(e)) { this.durationTimer.stop(); return Mono.just(ShouldRetryResult.noRetryOnNonRelatedException()); } logger.warn("Received retriable web exception, will retry", e); return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } @Override public RetryContext getRetryContext() { return this.retryContext; } private Boolean isOutOfRetries() { return this.retryCountTimeout >= this.timeoutPolicy.totalRetryCount(); } private Mono<ShouldRetryResult> shouldRetryAddressRefresh() { logger .warn("shouldRetryAddressRefresh() Retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}, shouldForcedAddressRefresh = {}, " + "shouldForceCollectionRoutingMapRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.retryCountTimeout, this.request.isAddressRefresh(), this.request.shouldForceAddressRefresh(), this.request.forceCollectionRoutingMapRefresh); return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } }
class WebExceptionRetryPolicy implements IRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(WebExceptionRetryPolicy.class); private StopWatch durationTimer = new StopWatch(); private RetryContext retryContext; private int retryDelay; private RxDocumentServiceRequest request; private HttpTimeoutPolicy timeoutPolicy; private boolean isReadRequest; private int retryCount = 0; private URI locationEndpoint; private boolean isOutOfRetries; public WebExceptionRetryPolicy() { durationTimer.start(); } public WebExceptionRetryPolicy(RetryContext retryContext) { durationTimer.start(); this.retryContext = retryContext; this.timeoutPolicy = HttpTimeoutPolicyDefault.INSTANCE; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception e) { if (isOutOfRetries) { this.durationTimer.stop(); return Mono.just(ShouldRetryResult.noRetry()); } CosmosException webException = Utils.as(e, CosmosException.class); if (WebExceptionUtility.isNetworkFailure(e) && this.isReadRequest && (webException != null && WebExceptionUtility.isReadTimeoutException(webException) && Exceptions.isSubStatusCode(webException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT))) { if (this.request.isAddressRefresh()) { return shouldRetryAddressRefresh(); } return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } if (!WebExceptionUtility.isWebExceptionRetriable(e)) { this.durationTimer.stop(); return Mono.just(ShouldRetryResult.noRetryOnNonRelatedException()); } logger.warn("Received retriable web exception, will retry", e); return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } @Override public RetryContext getRetryContext() { return this.retryContext; } private boolean isOutOfRetries() { return this.retryCount >= this.timeoutPolicy.totalRetryCount(); } private Mono<ShouldRetryResult> shouldRetryAddressRefresh() { if (isOutOfRetries) { logger .warn( "shouldRetryAddressRefresh() No more retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.retryCount, this.request.isAddressRefresh()); return Mono.just(ShouldRetryResult.noRetry()); } logger .warn("shouldRetryAddressRefresh() Retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}, shouldForcedAddressRefresh = {}, " + "shouldForceCollectionRoutingMapRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.retryCount, this.request.isAddressRefresh(), this.request.shouldForceAddressRefresh(), this.request.forceCollectionRoutingMapRefresh); return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } }
I am making use of the retryContext.retryCount to increase the retryCountTimeout in the code.
public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.request = request; this.isReadRequest = request.isReadOnlyRequest(); this.timeoutPolicy = HttpTimeoutPolicy.getTimeoutPolicy(request); if (this.retryContext != null) { this.retryCountTimeout = this.retryContext.getRetryCount(); } if (!isOutOfRetries()) { ResponseTimeoutAndDelays current = timeoutPolicy.getTimeoutAndDelaysList().get(this.retryCountTimeout); this.request.setResponseTimeout(current.getResponseTimeout()); this.retryDelay = current.getDelayForNextRequestInSeconds(); } this.locationEndpoint = request.requestContext.locationEndpointToRoute; }
this.retryCountTimeout = this.retryContext.getRetryCount();
public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.request = request; this.isReadRequest = request.isReadOnlyRequest(); this.timeoutPolicy = HttpTimeoutPolicy.getTimeoutPolicy(request); this.isOutOfRetries = isOutOfRetries(); if (!isOutOfRetries) { ResponseTimeoutAndDelays current = timeoutPolicy.getTimeoutAndDelaysList().get(this.retryCount); this.request.setResponseTimeout(current.getResponseTimeout()); this.retryDelay = current.getDelayForNextRequestInSeconds(); } this.retryCount++; this.locationEndpoint = request.requestContext.locationEndpointToRoute; }
class WebExceptionRetryPolicy implements IRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(WebExceptionRetryPolicy.class); private StopWatch durationTimer = new StopWatch(); private RetryContext retryContext; private int retryDelay; private RxDocumentServiceRequest request; private HttpTimeoutPolicy timeoutPolicy; private boolean isReadRequest; private int retryCountTimeout = 0; private URI locationEndpoint; public WebExceptionRetryPolicy() { durationTimer.start(); } public WebExceptionRetryPolicy(RetryContext retryContext) { durationTimer.start(); this.retryContext = retryContext; this.timeoutPolicy = HttpTimeoutPolicyDefault.INSTANCE; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception e) { boolean isOutOfRetries = isOutOfRetries(); if (isOutOfRetries) { this.durationTimer.stop(); return Mono.just(ShouldRetryResult.noRetry()); } CosmosException webException = Utils.as(e, CosmosException.class); if (WebExceptionUtility.isNetworkFailure(e) && this.isReadRequest && (webException != null && WebExceptionUtility.isReadTimeoutException(webException) && Exceptions.isSubStatusCode(webException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT))) { if (this.request.isAddressRefresh()) { return shouldRetryAddressRefresh(); } return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } if (!WebExceptionUtility.isWebExceptionRetriable(e)) { this.durationTimer.stop(); return Mono.just(ShouldRetryResult.noRetryOnNonRelatedException()); } logger.warn("Received retriable web exception, will retry", e); return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } @Override public RetryContext getRetryContext() { return this.retryContext; } private Boolean isOutOfRetries() { return this.retryCountTimeout >= this.timeoutPolicy.totalRetryCount(); } private Mono<ShouldRetryResult> shouldRetryAddressRefresh() { logger .warn("shouldRetryAddressRefresh() Retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}, shouldForcedAddressRefresh = {}, " + "shouldForceCollectionRoutingMapRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.retryCountTimeout, this.request.isAddressRefresh(), this.request.shouldForceAddressRefresh(), this.request.forceCollectionRoutingMapRefresh); return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } }
class WebExceptionRetryPolicy implements IRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(WebExceptionRetryPolicy.class); private StopWatch durationTimer = new StopWatch(); private RetryContext retryContext; private int retryDelay; private RxDocumentServiceRequest request; private HttpTimeoutPolicy timeoutPolicy; private boolean isReadRequest; private int retryCount = 0; private URI locationEndpoint; private boolean isOutOfRetries; public WebExceptionRetryPolicy() { durationTimer.start(); } public WebExceptionRetryPolicy(RetryContext retryContext) { durationTimer.start(); this.retryContext = retryContext; this.timeoutPolicy = HttpTimeoutPolicyDefault.INSTANCE; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception e) { if (isOutOfRetries) { this.durationTimer.stop(); return Mono.just(ShouldRetryResult.noRetry()); } CosmosException webException = Utils.as(e, CosmosException.class); if (WebExceptionUtility.isNetworkFailure(e) && this.isReadRequest && (webException != null && WebExceptionUtility.isReadTimeoutException(webException) && Exceptions.isSubStatusCode(webException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT))) { if (this.request.isAddressRefresh()) { return shouldRetryAddressRefresh(); } return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } if (!WebExceptionUtility.isWebExceptionRetriable(e)) { this.durationTimer.stop(); return Mono.just(ShouldRetryResult.noRetryOnNonRelatedException()); } logger.warn("Received retriable web exception, will retry", e); return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } @Override public RetryContext getRetryContext() { return this.retryContext; } private boolean isOutOfRetries() { return this.retryCount >= this.timeoutPolicy.totalRetryCount(); } private Mono<ShouldRetryResult> shouldRetryAddressRefresh() { if (isOutOfRetries) { logger .warn( "shouldRetryAddressRefresh() No more retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.retryCount, this.request.isAddressRefresh()); return Mono.just(ShouldRetryResult.noRetry()); } logger .warn("shouldRetryAddressRefresh() Retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}, shouldForcedAddressRefresh = {}, " + "shouldForceCollectionRoutingMapRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.retryCount, this.request.isAddressRefresh(), this.request.shouldForceAddressRefresh(), this.request.forceCollectionRoutingMapRefresh); return Mono.just(ShouldRetryResult.retryAfter(Duration.ofSeconds(retryDelay))); } }
This is an invalid token needed for tests validation. It replaces the real token in response with the dummy token.
HttpPipeline getHttpPipeline(HttpClient httpClient) { String accountId = getAccountId(); String accountDomain = getAccountDomain(); AzureKeyCredential keyCredential = getAccountKey(); TokenCredential credential = constructAccountKeyCredential(accountId, keyCredential); String endpoint = AuthenticationEndpoint.constructFromDomain(accountDomain); String authenticationScope = AuthenticationEndpoint.constructScope(endpoint); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BearerTokenAuthenticationPolicy(credential, authenticationScope)); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..AccessToken", null, "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0.", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); policies.add(interceptorManager.getRecordPolicy()); } else if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("X-MRC-CV"))); interceptorManager.addMatchers(customMatchers); } HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); return pipeline; }
customSanitizers.add(new TestProxySanitizer("$..AccessToken", null, "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0.", TestProxySanitizerType.BODY_KEY));
HttpPipeline getHttpPipeline(HttpClient httpClient) { String accountId = getAccountId(); String accountDomain = getAccountDomain(); AzureKeyCredential keyCredential = getAccountKey(); TokenCredential credential = constructAccountKeyCredential(accountId, keyCredential); String endpoint = AuthenticationEndpoint.constructFromDomain(accountDomain); String authenticationScope = AuthenticationEndpoint.constructScope(endpoint); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BearerTokenAuthenticationPolicy(credential, authenticationScope)); if (interceptorManager.isRecordMode() || interceptorManager.isPlaybackMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..AccessToken", null, INVALID_DUMMY_TOKEN, TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("X-MRC-CV"))); interceptorManager.addMatchers(customMatchers); } HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); return pipeline; }
class MixedRealityStsClientTestBase extends TestProxyTestBase { private final String accountDomain = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_DOMAIN"); private final String accountId = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_ID"); private final String accountKey = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_KEY"); private final String playbackAccountDomain = "mixedreality.azure.com"; private final String playbackAccountId = "f5b3e69f-1e1b-46a5-a718-aea58a7a0f8e"; private final String playbackAccountKey = "NjgzMjFkNWEtNzk3OC00Y2ViLWI4ODAtMGY0OTc1MWRhYWU5"; String getAccountDomain() { return interceptorManager.isPlaybackMode() ? this.playbackAccountDomain : this.accountDomain; } String getAccountId() { String accountIdValue = interceptorManager.isPlaybackMode() ? this.playbackAccountId : this.accountId; return accountIdValue; } AzureKeyCredential getAccountKey() { String accountKeyValue = interceptorManager.isPlaybackMode() ? this.playbackAccountKey : this.accountKey; return new AzureKeyCredential(accountKeyValue); } static TokenCredential constructAccountKeyCredential(String accountId, AzureKeyCredential keyCredential) { return new MixedRealityAccountKeyCredential(UUID.fromString(accountId), keyCredential); } }
class MixedRealityStsClientTestBase extends TestProxyTestBase { public static final String INVALID_DUMMY_TOKEN = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b" + "3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZm" + "F1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0."; private final String accountDomain = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_DOMAIN"); private final String accountId = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_ID"); private final String accountKey = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_KEY"); private final String playbackAccountDomain = "mixedreality.azure.com"; private final String playbackAccountId = "f5b3e69f-1e1b-46a5-a718-aea58a7a0f8e"; private final String playbackAccountKey = "NjgzMjFkNWEtNzk3OC00Y2ViLWI4ODAtMGY0OTc1MWRhYWU5"; String getAccountDomain() { return interceptorManager.isPlaybackMode() ? this.playbackAccountDomain : this.accountDomain; } String getAccountId() { String accountIdValue = interceptorManager.isPlaybackMode() ? this.playbackAccountId : this.accountId; return accountIdValue; } AzureKeyCredential getAccountKey() { String accountKeyValue = interceptorManager.isPlaybackMode() ? this.playbackAccountKey : this.accountKey; return new AzureKeyCredential(accountKeyValue); } static TokenCredential constructAccountKeyCredential(String accountId, AzureKeyCredential keyCredential) { return new MixedRealityAccountKeyCredential(UUID.fromString(accountId), keyCredential); } }
sanitizers are to be added in both playback and record mode to match correctly with redacted content.
HttpPipeline getHttpPipeline(HttpClient httpClient) { String accountId = getAccountId(); String accountDomain = getAccountDomain(); AzureKeyCredential keyCredential = getAccountKey(); TokenCredential credential = constructAccountKeyCredential(accountId, keyCredential); String endpoint = AuthenticationEndpoint.constructFromDomain(accountDomain); String authenticationScope = AuthenticationEndpoint.constructScope(endpoint); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BearerTokenAuthenticationPolicy(credential, authenticationScope)); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..AccessToken", null, "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0.", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); policies.add(interceptorManager.getRecordPolicy()); } else if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("X-MRC-CV"))); interceptorManager.addMatchers(customMatchers); } HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); return pipeline; }
if (interceptorManager.isRecordMode()) {
HttpPipeline getHttpPipeline(HttpClient httpClient) { String accountId = getAccountId(); String accountDomain = getAccountDomain(); AzureKeyCredential keyCredential = getAccountKey(); TokenCredential credential = constructAccountKeyCredential(accountId, keyCredential); String endpoint = AuthenticationEndpoint.constructFromDomain(accountDomain); String authenticationScope = AuthenticationEndpoint.constructScope(endpoint); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BearerTokenAuthenticationPolicy(credential, authenticationScope)); if (interceptorManager.isRecordMode() || interceptorManager.isPlaybackMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..AccessToken", null, INVALID_DUMMY_TOKEN, TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("X-MRC-CV"))); interceptorManager.addMatchers(customMatchers); } HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); return pipeline; }
class MixedRealityStsClientTestBase extends TestProxyTestBase { private final String accountDomain = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_DOMAIN"); private final String accountId = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_ID"); private final String accountKey = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_KEY"); private final String playbackAccountDomain = "mixedreality.azure.com"; private final String playbackAccountId = "f5b3e69f-1e1b-46a5-a718-aea58a7a0f8e"; private final String playbackAccountKey = "NjgzMjFkNWEtNzk3OC00Y2ViLWI4ODAtMGY0OTc1MWRhYWU5"; String getAccountDomain() { return interceptorManager.isPlaybackMode() ? this.playbackAccountDomain : this.accountDomain; } String getAccountId() { String accountIdValue = interceptorManager.isPlaybackMode() ? this.playbackAccountId : this.accountId; return accountIdValue; } AzureKeyCredential getAccountKey() { String accountKeyValue = interceptorManager.isPlaybackMode() ? this.playbackAccountKey : this.accountKey; return new AzureKeyCredential(accountKeyValue); } static TokenCredential constructAccountKeyCredential(String accountId, AzureKeyCredential keyCredential) { return new MixedRealityAccountKeyCredential(UUID.fromString(accountId), keyCredential); } }
class MixedRealityStsClientTestBase extends TestProxyTestBase { public static final String INVALID_DUMMY_TOKEN = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b" + "3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZm" + "F1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0."; private final String accountDomain = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_DOMAIN"); private final String accountId = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_ID"); private final String accountKey = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_KEY"); private final String playbackAccountDomain = "mixedreality.azure.com"; private final String playbackAccountId = "f5b3e69f-1e1b-46a5-a718-aea58a7a0f8e"; private final String playbackAccountKey = "NjgzMjFkNWEtNzk3OC00Y2ViLWI4ODAtMGY0OTc1MWRhYWU5"; String getAccountDomain() { return interceptorManager.isPlaybackMode() ? this.playbackAccountDomain : this.accountDomain; } String getAccountId() { String accountIdValue = interceptorManager.isPlaybackMode() ? this.playbackAccountId : this.accountId; return accountIdValue; } AzureKeyCredential getAccountKey() { String accountKeyValue = interceptorManager.isPlaybackMode() ? this.playbackAccountKey : this.accountKey; return new AzureKeyCredential(accountKeyValue); } static TokenCredential constructAccountKeyCredential(String accountId, AzureKeyCredential keyCredential) { return new MixedRealityAccountKeyCredential(UUID.fromString(accountId), keyCredential); } }
I assume that's applicable only if we're custom redacting RequestUri and Headers ? as those are what's used to match the request ? Else, I should see failures in CI.
HttpPipeline getHttpPipeline(HttpClient httpClient) { String accountId = getAccountId(); String accountDomain = getAccountDomain(); AzureKeyCredential keyCredential = getAccountKey(); TokenCredential credential = constructAccountKeyCredential(accountId, keyCredential); String endpoint = AuthenticationEndpoint.constructFromDomain(accountDomain); String authenticationScope = AuthenticationEndpoint.constructScope(endpoint); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BearerTokenAuthenticationPolicy(credential, authenticationScope)); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..AccessToken", null, "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0.", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); policies.add(interceptorManager.getRecordPolicy()); } else if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("X-MRC-CV"))); interceptorManager.addMatchers(customMatchers); } HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); return pipeline; }
if (interceptorManager.isRecordMode()) {
HttpPipeline getHttpPipeline(HttpClient httpClient) { String accountId = getAccountId(); String accountDomain = getAccountDomain(); AzureKeyCredential keyCredential = getAccountKey(); TokenCredential credential = constructAccountKeyCredential(accountId, keyCredential); String endpoint = AuthenticationEndpoint.constructFromDomain(accountDomain); String authenticationScope = AuthenticationEndpoint.constructScope(endpoint); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BearerTokenAuthenticationPolicy(credential, authenticationScope)); if (interceptorManager.isRecordMode() || interceptorManager.isPlaybackMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..AccessToken", null, INVALID_DUMMY_TOKEN, TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("X-MRC-CV"))); interceptorManager.addMatchers(customMatchers); } HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); return pipeline; }
class MixedRealityStsClientTestBase extends TestProxyTestBase { private final String accountDomain = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_DOMAIN"); private final String accountId = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_ID"); private final String accountKey = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_KEY"); private final String playbackAccountDomain = "mixedreality.azure.com"; private final String playbackAccountId = "f5b3e69f-1e1b-46a5-a718-aea58a7a0f8e"; private final String playbackAccountKey = "NjgzMjFkNWEtNzk3OC00Y2ViLWI4ODAtMGY0OTc1MWRhYWU5"; String getAccountDomain() { return interceptorManager.isPlaybackMode() ? this.playbackAccountDomain : this.accountDomain; } String getAccountId() { String accountIdValue = interceptorManager.isPlaybackMode() ? this.playbackAccountId : this.accountId; return accountIdValue; } AzureKeyCredential getAccountKey() { String accountKeyValue = interceptorManager.isPlaybackMode() ? this.playbackAccountKey : this.accountKey; return new AzureKeyCredential(accountKeyValue); } static TokenCredential constructAccountKeyCredential(String accountId, AzureKeyCredential keyCredential) { return new MixedRealityAccountKeyCredential(UUID.fromString(accountId), keyCredential); } }
class MixedRealityStsClientTestBase extends TestProxyTestBase { public static final String INVALID_DUMMY_TOKEN = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b" + "3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZm" + "F1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0."; private final String accountDomain = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_DOMAIN"); private final String accountId = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_ID"); private final String accountKey = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_KEY"); private final String playbackAccountDomain = "mixedreality.azure.com"; private final String playbackAccountId = "f5b3e69f-1e1b-46a5-a718-aea58a7a0f8e"; private final String playbackAccountKey = "NjgzMjFkNWEtNzk3OC00Y2ViLWI4ODAtMGY0OTc1MWRhYWU5"; String getAccountDomain() { return interceptorManager.isPlaybackMode() ? this.playbackAccountDomain : this.accountDomain; } String getAccountId() { String accountIdValue = interceptorManager.isPlaybackMode() ? this.playbackAccountId : this.accountId; return accountIdValue; } AzureKeyCredential getAccountKey() { String accountKeyValue = interceptorManager.isPlaybackMode() ? this.playbackAccountKey : this.accountKey; return new AzureKeyCredential(accountKeyValue); } static TokenCredential constructAccountKeyCredential(String accountId, AzureKeyCredential keyCredential) { return new MixedRealityAccountKeyCredential(UUID.fromString(accountId), keyCredential); } }
```suggestion customSanitizers.add(new TestProxySanitizer("$..AccessToken", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); ```
HttpPipeline getHttpPipeline(HttpClient httpClient) { String accountId = getAccountId(); String accountDomain = getAccountDomain(); AzureKeyCredential keyCredential = getAccountKey(); TokenCredential credential = constructAccountKeyCredential(accountId, keyCredential); String endpoint = AuthenticationEndpoint.constructFromDomain(accountDomain); String authenticationScope = AuthenticationEndpoint.constructScope(endpoint); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BearerTokenAuthenticationPolicy(credential, authenticationScope)); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..AccessToken", null, "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0.", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); policies.add(interceptorManager.getRecordPolicy()); } else if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("X-MRC-CV"))); interceptorManager.addMatchers(customMatchers); } HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); return pipeline; }
customSanitizers.add(new TestProxySanitizer("$..AccessToken", null, "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0.", TestProxySanitizerType.BODY_KEY));
HttpPipeline getHttpPipeline(HttpClient httpClient) { String accountId = getAccountId(); String accountDomain = getAccountDomain(); AzureKeyCredential keyCredential = getAccountKey(); TokenCredential credential = constructAccountKeyCredential(accountId, keyCredential); String endpoint = AuthenticationEndpoint.constructFromDomain(accountDomain); String authenticationScope = AuthenticationEndpoint.constructScope(endpoint); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BearerTokenAuthenticationPolicy(credential, authenticationScope)); if (interceptorManager.isRecordMode() || interceptorManager.isPlaybackMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..AccessToken", null, INVALID_DUMMY_TOKEN, TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("X-MRC-CV"))); interceptorManager.addMatchers(customMatchers); } HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); return pipeline; }
class MixedRealityStsClientTestBase extends TestProxyTestBase { private final String accountDomain = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_DOMAIN"); private final String accountId = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_ID"); private final String accountKey = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_KEY"); private final String playbackAccountDomain = "mixedreality.azure.com"; private final String playbackAccountId = "f5b3e69f-1e1b-46a5-a718-aea58a7a0f8e"; private final String playbackAccountKey = "NjgzMjFkNWEtNzk3OC00Y2ViLWI4ODAtMGY0OTc1MWRhYWU5"; String getAccountDomain() { return interceptorManager.isPlaybackMode() ? this.playbackAccountDomain : this.accountDomain; } String getAccountId() { String accountIdValue = interceptorManager.isPlaybackMode() ? this.playbackAccountId : this.accountId; return accountIdValue; } AzureKeyCredential getAccountKey() { String accountKeyValue = interceptorManager.isPlaybackMode() ? this.playbackAccountKey : this.accountKey; return new AzureKeyCredential(accountKeyValue); } static TokenCredential constructAccountKeyCredential(String accountId, AzureKeyCredential keyCredential) { return new MixedRealityAccountKeyCredential(UUID.fromString(accountId), keyCredential); } }
class MixedRealityStsClientTestBase extends TestProxyTestBase { public static final String INVALID_DUMMY_TOKEN = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b" + "3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZm" + "F1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0."; private final String accountDomain = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_DOMAIN"); private final String accountId = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_ID"); private final String accountKey = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_KEY"); private final String playbackAccountDomain = "mixedreality.azure.com"; private final String playbackAccountId = "f5b3e69f-1e1b-46a5-a718-aea58a7a0f8e"; private final String playbackAccountKey = "NjgzMjFkNWEtNzk3OC00Y2ViLWI4ODAtMGY0OTc1MWRhYWU5"; String getAccountDomain() { return interceptorManager.isPlaybackMode() ? this.playbackAccountDomain : this.accountDomain; } String getAccountId() { String accountIdValue = interceptorManager.isPlaybackMode() ? this.playbackAccountId : this.accountId; return accountIdValue; } AzureKeyCredential getAccountKey() { String accountKeyValue = interceptorManager.isPlaybackMode() ? this.playbackAccountKey : this.accountKey; return new AzureKeyCredential(accountKeyValue); } static TokenCredential constructAccountKeyCredential(String accountId, AzureKeyCredential keyCredential) { return new MixedRealityAccountKeyCredential(UUID.fromString(accountId), keyCredential); } }
We pull up the match using the request URI but after that we just match everything, I see you have added BodilessMatcher it coul be why we don't see the match errors.
HttpPipeline getHttpPipeline(HttpClient httpClient) { String accountId = getAccountId(); String accountDomain = getAccountDomain(); AzureKeyCredential keyCredential = getAccountKey(); TokenCredential credential = constructAccountKeyCredential(accountId, keyCredential); String endpoint = AuthenticationEndpoint.constructFromDomain(accountDomain); String authenticationScope = AuthenticationEndpoint.constructScope(endpoint); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BearerTokenAuthenticationPolicy(credential, authenticationScope)); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..AccessToken", null, "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0.", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); policies.add(interceptorManager.getRecordPolicy()); } else if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("X-MRC-CV"))); interceptorManager.addMatchers(customMatchers); } HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); return pipeline; }
if (interceptorManager.isRecordMode()) {
HttpPipeline getHttpPipeline(HttpClient httpClient) { String accountId = getAccountId(); String accountDomain = getAccountDomain(); AzureKeyCredential keyCredential = getAccountKey(); TokenCredential credential = constructAccountKeyCredential(accountId, keyCredential); String endpoint = AuthenticationEndpoint.constructFromDomain(accountDomain); String authenticationScope = AuthenticationEndpoint.constructScope(endpoint); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BearerTokenAuthenticationPolicy(credential, authenticationScope)); if (interceptorManager.isRecordMode() || interceptorManager.isPlaybackMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..AccessToken", null, INVALID_DUMMY_TOKEN, TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("X-MRC-CV"))); interceptorManager.addMatchers(customMatchers); } HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); return pipeline; }
class MixedRealityStsClientTestBase extends TestProxyTestBase { private final String accountDomain = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_DOMAIN"); private final String accountId = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_ID"); private final String accountKey = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_KEY"); private final String playbackAccountDomain = "mixedreality.azure.com"; private final String playbackAccountId = "f5b3e69f-1e1b-46a5-a718-aea58a7a0f8e"; private final String playbackAccountKey = "NjgzMjFkNWEtNzk3OC00Y2ViLWI4ODAtMGY0OTc1MWRhYWU5"; String getAccountDomain() { return interceptorManager.isPlaybackMode() ? this.playbackAccountDomain : this.accountDomain; } String getAccountId() { String accountIdValue = interceptorManager.isPlaybackMode() ? this.playbackAccountId : this.accountId; return accountIdValue; } AzureKeyCredential getAccountKey() { String accountKeyValue = interceptorManager.isPlaybackMode() ? this.playbackAccountKey : this.accountKey; return new AzureKeyCredential(accountKeyValue); } static TokenCredential constructAccountKeyCredential(String accountId, AzureKeyCredential keyCredential) { return new MixedRealityAccountKeyCredential(UUID.fromString(accountId), keyCredential); } }
class MixedRealityStsClientTestBase extends TestProxyTestBase { public static final String INVALID_DUMMY_TOKEN = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b" + "3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZm" + "F1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0."; private final String accountDomain = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_DOMAIN"); private final String accountId = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_ID"); private final String accountKey = Configuration.getGlobalConfiguration().get("MIXEDREALITY_ACCOUNT_KEY"); private final String playbackAccountDomain = "mixedreality.azure.com"; private final String playbackAccountId = "f5b3e69f-1e1b-46a5-a718-aea58a7a0f8e"; private final String playbackAccountKey = "NjgzMjFkNWEtNzk3OC00Y2ViLWI4ODAtMGY0OTc1MWRhYWU5"; String getAccountDomain() { return interceptorManager.isPlaybackMode() ? this.playbackAccountDomain : this.accountDomain; } String getAccountId() { String accountIdValue = interceptorManager.isPlaybackMode() ? this.playbackAccountId : this.accountId; return accountIdValue; } AzureKeyCredential getAccountKey() { String accountKeyValue = interceptorManager.isPlaybackMode() ? this.playbackAccountKey : this.accountKey; return new AzureKeyCredential(accountKeyValue); } static TokenCredential constructAccountKeyCredential(String accountId, AzureKeyCredential keyCredential) { return new MixedRealityAccountKeyCredential(UUID.fromString(accountId), keyCredential); } }